diff --git a/.gitignore b/.gitignore index 4034909d..aa4cfe28 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ *.so *.dylib *.PID +*.meta # Test binary, build with `go test -c` *.test @@ -26,3 +27,81 @@ debug examples/testing/server examples/demo/cluster_grpc/main +build +bin +obj +out +.vs + +# Unity 3D + +# This .gitignore file should be placed at the root of your Unity project directory +# +# Get latest from https://github.com/github/gitignore/blob/master/Unity.gitignore +# +/[Ll]ibrary/ +/[Tt]emp/ +/[Oo]bj/ +/[Bb]uild/ +/[Bb]uilds/ +/[Ll]ogs/ +/[Uu]ser[Ss]ettings/ + +# MemoryCaptures can get excessive in size. +# They also could contain extremely sensitive data +/[Mm]emoryCaptures/ + +# Asset meta data should only be ignored when the corresponding asset is also ignored +!/[Aa]ssets/**/*.meta + +# Uncomment this line if you wish to ignore the asset store tools plugin +# /[Aa]ssets/AssetStoreTools* + +# Autogenerated Jetbrains Rider plugin +/[Aa]ssets/Plugins/Editor/JetBrains* + +# Visual Studio cache directory +.vs/ + +# Gradle cache directory +.gradle/ + +# Autogenerated VS/MD/Consulo solution and project files +ExportedObj/ +.consulo/ +*.unityproj +*.sln +*.suo +*.tmp +*.user +*.userprefs +*.pidb +*.booproj +*.svd +*.pdb +*.mdb +*.opendb +*.VC.db + +# Unity3D generated meta files +*.pidb.meta +*.pdb.meta +*.mdb.meta + +# Unity3D generated file on crash reports +sysinfo.txt + +# Builds +*.apk +*.aab +*.unitypackage + +# Crashlytics generated file +crashlytics-build.properties + +# Packed Addressables +/[Aa]ssets/[Aa]ddressable[Aa]ssets[Dd]ata/*/*.bin* + +# Temporary auto-generated Android Assets +/[Aa]ssets/[Ss]treamingAssets/aa.meta +/[Aa]ssets/[Ss]treamingAssets/aa/* diff --git a/.gitmodules b/.gitmodules index b8e51447..40b8017c 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ -[submodule "protos"] +[submodule "pitaya-protos"] path = pitaya-protos - url = https://github.com/topfreegames/pitaya-protos + url = git@github.com:topfreegames/pitaya-protos.git diff --git a/Makefile b/Makefile index aefa1669..589934b0 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,21 @@ -TESTABLE_PACKAGES = `go list ./... | grep -v examples | grep -v constants | grep -v mocks | grep -v helpers | grep -v interfaces | grep -v protos | grep -v e2e | grep -v benchmark` + +ifeq ($(OS), Windows_NT) + BIN := pitaya.exe + MKFOLDER := if not exist "build" mkdir build + GREP_CMD := findstr /V +else + BIN := pitaya + MKFOLDER := mkdir -p build + GREP_CMD := grep -v +endif + +TESTABLE_PACKAGES = $(shell go list ./... | $(GREP_CMD) examples | $(GREP_CMD) constants | $(GREP_CMD) mocks | $(GREP_CMD) helpers | $(GREP_CMD) interfaces | $(GREP_CMD) protos | $(GREP_CMD) e2e | $(GREP_CMD) benchmark) + +.PHONY: build + +build: + @$(MKFOLDER) + @go build -o build/$(BIN) setup: init-submodules @go get ./... @@ -55,8 +72,9 @@ protos-compile-demo: protos-compile: @cd benchmark/testdata && ./gen_proto.sh - @protoc -I pitaya-protos/ pitaya-protos/*.proto --go_out=plugins=grpc:protos - @protoc -I pitaya-protos/test pitaya-protos/test/*.proto --go_out=protos/test + @protoc -I pitaya-protos/ pitaya-protos/*.proto --go_out=./pkg/protos/ --go_opt paths=source_relative --go-grpc_out ./pkg/protos/ --go-grpc_opt paths=source_relative --go-grpc_opt require_unimplemented_servers=false + @protoc -I pitaya-protos/test pitaya-protos/test/*.proto --go_out ./pkg/protos/test/ --go_opt paths=source_relative + @protoc -I examples/demo/protos/ examples/demo/protos/*.proto --go_out ./examples/demo/protos --go_opt paths=source_relative rm-test-temp-files: @rm -f cluster/127.0.0.1* 127.0.0.1* @@ -141,26 +159,29 @@ test-coverage-func coverage-func: test-coverage merge-profiles @echo "\033[1;34m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\033[0m" @go tool cover -func=coverage-all.out | egrep -v "100.0[%]" -mocks: agent-mock session-mock networkentity-mock pitaya-mock serializer-mock metrics-mock acceptor-mock +mocks: agent-mock session-mock networkentity-mock pitaya-mock serializer-mock metrics-mock acceptor-mock cluster-mock agent-mock: - @mockgen github.com/topfreegames/pitaya/v2/agent Agent,AgentFactory | sed 's/mock_agent/mocks/' > agent/mocks/agent.go + @mockgen github.com/topfreegames/pitaya/v3/pkg/agent Agent,AgentFactory | sed 's/mock_agent/mocks/' > pkg/agent/mocks/agent.go session-mock: - @mockgen github.com/topfreegames/pitaya/v2/session Session,SessionPool | sed 's/mock_session/mocks/' > session/mocks/session.go + @mockgen github.com/topfreegames/pitaya/v3/pkg/session Session,SessionPool | sed 's/mock_session/mocks/' > pkg/session/mocks/session.go networkentity-mock: - @mockgen github.com/topfreegames/pitaya/v2/networkentity NetworkEntity | sed 's/mock_networkentity/mocks/' > networkentity/mocks/networkentity.go + @mockgen github.com/topfreegames/pitaya/v3/pkg/networkentity NetworkEntitgit y | sed 's/mock_networkentity/mocks/' > pkg/networkentity/mocks/networkentity.go pitaya-mock: - @mockgen github.com/topfreegames/pitaya/v2 Pitaya | sed 's/mock_v2/mocks/' > mocks/app.go + @mockgen github.com/topfreegames/pitaya/v3/pkg Pitaya | sed 's/mock_v2/mocks/' > pkg/mocks/app.go metrics-mock: - @mockgen github.com/topfreegames/pitaya/v2/metrics Reporter | sed 's/mock_metrics/mocks/' > metrics/mocks/reporter.go - @mockgen github.com/topfreegames/pitaya/v2/metrics Client | sed 's/mock_metrics/mocks/' > metrics/mocks/statsd_reporter.go + @mockgen github.com/topfreegames/pitaya/v3/pkg/metrics Reporter | sed 's/mock_metrics/mocks/' > pkg/metrics/mocks/reporter.go + @mockgen github.com/topfreegames/pitaya/v3/pkg/metrics Client | sed 's/mock_metrics/mocks/' > pkg/metrics/mocks/statsd_reporter.go serializer-mock: - @mockgen github.com/topfreegames/pitaya/v2/serialize Serializer | sed 's/mock_serialize/mocks/' > serialize/mocks/serializer.go + @mockgen github.com/topfreegames/pitaya/v3/pkg/serialize Serializer | sed 's/mock_serialize/mocks/' > pkg/serialize/mocks/serializer.go acceptor-mock: - @mockgen github.com/topfreegames/pitaya/v2/acceptor PlayerConn,Acceptor | sed 's/mock_acceptor/mocks/' > mocks/acceptor.go + @mockgen github.com/topfreegames/pitaya/v3/pkg/acceptor PlayerConn,Acceptor | sed 's/mock_acceptor/mocks/' > pkg/mocks/acceptor.go + +cluster-mock: + @mockgen github.com/topfreegames/pitaya/v3/pkg/cluster RPCServer,RPCClient,SDListener,RemoteBindingListener,InfoRetriever | sed 's/mock_cluster/mocks/' > pkg/cluster/mocks/cluster.go diff --git a/README.md b/README.md index 31f701af..50c10fe1 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ This command will run both unit and e2e tests. #TODO ## Authors -* **TFG Co** - Initial work +* **Wildlife Studios** - Initial work ## License [MIT License](./LICENSE) diff --git a/agent/mocks/agent.go b/agent/mocks/agent.go index de567a4c..d363f101 100644 --- a/agent/mocks/agent.go +++ b/agent/mocks/agent.go @@ -1,5 +1,5 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/topfreegames/pitaya/v2/agent (interfaces: Agent,AgentFactory) +// Source: github.com/topfreegames/pitaya/v3/pkg/agent (interfaces: Agent,AgentFactory) // Package mocks is a generated GoMock package. package mocks @@ -7,9 +7,9 @@ package mocks import ( context "context" gomock "github.com/golang/mock/gomock" - agent "github.com/topfreegames/pitaya/v2/agent" - protos "github.com/topfreegames/pitaya/v2/protos" - session "github.com/topfreegames/pitaya/v2/session" + agent "github.com/topfreegames/pitaya/v3/pkg/agent" + protos "github.com/topfreegames/pitaya/v3/pkg/protos" + session "github.com/topfreegames/pitaya/v3/pkg/session" net "net" reflect "reflect" ) diff --git a/benchmark/benchmark_test.go b/benchmark/benchmark_test.go index 7c267501..3dadf9a6 100644 --- a/benchmark/benchmark_test.go +++ b/benchmark/benchmark_test.go @@ -22,11 +22,11 @@ package benchmark import ( "fmt" + "github.com/topfreegames/pitaya/v3/pkg/client" "os" "testing" "github.com/sirupsen/logrus" - "github.com/topfreegames/pitaya/v2/client" ) var clients []*client.Client diff --git a/benchmark/testdata/gen_proto.sh b/benchmark/testdata/gen_proto.sh index a64567fa..9a27b25c 100755 --- a/benchmark/testdata/gen_proto.sh +++ b/benchmark/testdata/gen_proto.sh @@ -1 +1 @@ -protoc --go_out . *.proto +protoc --go_out=./ --go_opt=paths=source_relative *.proto diff --git a/benchmark/testdata/test.pb.go b/benchmark/testdata/test.pb.go index 1b4564c9..e425bc53 100644 --- a/benchmark/testdata/test.pb.go +++ b/benchmark/testdata/test.pb.go @@ -1,112 +1,206 @@ // Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 // source: test.proto package testdata -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) type Ping struct { - Content string `protobuf:"bytes,1,opt,name=Content" json:"Content,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields -func (m *Ping) Reset() { *m = Ping{} } -func (m *Ping) String() string { return proto.CompactTextString(m) } -func (*Ping) ProtoMessage() {} -func (*Ping) Descriptor() ([]byte, []int) { - return fileDescriptor_test_ab5a0806b9eb7ae2, []int{0} -} -func (m *Ping) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Ping.Unmarshal(m, b) + Content string `protobuf:"bytes,1,opt,name=Content,proto3" json:"Content,omitempty"` } -func (m *Ping) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Ping.Marshal(b, m, deterministic) -} -func (dst *Ping) XXX_Merge(src proto.Message) { - xxx_messageInfo_Ping.Merge(dst, src) + +func (x *Ping) Reset() { + *x = Ping{} + if protoimpl.UnsafeEnabled { + mi := &file_test_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Ping) XXX_Size() int { - return xxx_messageInfo_Ping.Size(m) + +func (x *Ping) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Ping) XXX_DiscardUnknown() { - xxx_messageInfo_Ping.DiscardUnknown(m) + +func (*Ping) ProtoMessage() {} + +func (x *Ping) ProtoReflect() protoreflect.Message { + mi := &file_test_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Ping proto.InternalMessageInfo +// Deprecated: Use Ping.ProtoReflect.Descriptor instead. +func (*Ping) Descriptor() ([]byte, []int) { + return file_test_proto_rawDescGZIP(), []int{0} +} -func (m *Ping) GetContent() string { - if m != nil { - return m.Content +func (x *Ping) GetContent() string { + if x != nil { + return x.Content } return "" } type Pong struct { - Content string `protobuf:"bytes,2,opt,name=Content" json:"Content,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields -func (m *Pong) Reset() { *m = Pong{} } -func (m *Pong) String() string { return proto.CompactTextString(m) } -func (*Pong) ProtoMessage() {} -func (*Pong) Descriptor() ([]byte, []int) { - return fileDescriptor_test_ab5a0806b9eb7ae2, []int{1} -} -func (m *Pong) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Pong.Unmarshal(m, b) + Content string `protobuf:"bytes,2,opt,name=Content,proto3" json:"Content,omitempty"` } -func (m *Pong) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Pong.Marshal(b, m, deterministic) -} -func (dst *Pong) XXX_Merge(src proto.Message) { - xxx_messageInfo_Pong.Merge(dst, src) + +func (x *Pong) Reset() { + *x = Pong{} + if protoimpl.UnsafeEnabled { + mi := &file_test_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } } -func (m *Pong) XXX_Size() int { - return xxx_messageInfo_Pong.Size(m) + +func (x *Pong) String() string { + return protoimpl.X.MessageStringOf(x) } -func (m *Pong) XXX_DiscardUnknown() { - xxx_messageInfo_Pong.DiscardUnknown(m) + +func (*Pong) ProtoMessage() {} + +func (x *Pong) ProtoReflect() protoreflect.Message { + mi := &file_test_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) } -var xxx_messageInfo_Pong proto.InternalMessageInfo +// Deprecated: Use Pong.ProtoReflect.Descriptor instead. +func (*Pong) Descriptor() ([]byte, []int) { + return file_test_proto_rawDescGZIP(), []int{1} +} -func (m *Pong) GetContent() string { - if m != nil { - return m.Content +func (x *Pong) GetContent() string { + if x != nil { + return x.Content } return "" } -func init() { - proto.RegisterType((*Ping)(nil), "testdata.Ping") - proto.RegisterType((*Pong)(nil), "testdata.Pong") +var File_test_proto protoreflect.FileDescriptor + +var file_test_proto_rawDesc = []byte{ + 0x0a, 0x0a, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x74, 0x65, + 0x73, 0x74, 0x64, 0x61, 0x74, 0x61, 0x22, 0x20, 0x0a, 0x04, 0x50, 0x69, 0x6e, 0x67, 0x12, 0x18, + 0x0a, 0x07, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x07, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x22, 0x20, 0x0a, 0x04, 0x50, 0x6f, 0x6e, 0x67, + 0x12, 0x18, 0x0a, 0x07, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x07, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x42, 0x33, 0x5a, 0x31, 0x67, 0x69, + 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, + 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2f, 0x62, 0x65, 0x6e, + 0x63, 0x68, 0x6d, 0x61, 0x72, 0x6b, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x64, 0x61, 0x74, 0x61, 0x62, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_test_proto_rawDescOnce sync.Once + file_test_proto_rawDescData = file_test_proto_rawDesc +) + +func file_test_proto_rawDescGZIP() []byte { + file_test_proto_rawDescOnce.Do(func() { + file_test_proto_rawDescData = protoimpl.X.CompressGZIP(file_test_proto_rawDescData) + }) + return file_test_proto_rawDescData } -func init() { proto.RegisterFile("test.proto", fileDescriptor_test_ab5a0806b9eb7ae2) } +var file_test_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_test_proto_goTypes = []interface{}{ + (*Ping)(nil), // 0: testdata.Ping + (*Pong)(nil), // 1: testdata.Pong +} +var file_test_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 +} -var fileDescriptor_test_ab5a0806b9eb7ae2 = []byte{ - // 85 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2a, 0x49, 0x2d, 0x2e, - 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x00, 0xb1, 0x53, 0x12, 0x4b, 0x12, 0x95, 0x14, - 0xb8, 0x58, 0x02, 0x32, 0xf3, 0xd2, 0x85, 0x24, 0xb8, 0xd8, 0x9d, 0xf3, 0xf3, 0x4a, 0x52, 0xf3, - 0x4a, 0x24, 0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0x60, 0x5c, 0xb0, 0x8a, 0x7c, 0x54, 0x15, 0x4c, - 0x28, 0x2a, 0x92, 0xd8, 0xc0, 0x86, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x01, 0xcd, 0x56, - 0xda, 0x62, 0x00, 0x00, 0x00, +func init() { file_test_proto_init() } +func file_test_proto_init() { + if File_test_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_test_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Ping); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_test_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Pong); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_test_proto_rawDesc, + NumEnums: 0, + NumMessages: 2, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_test_proto_goTypes, + DependencyIndexes: file_test_proto_depIdxs, + MessageInfos: file_test_proto_msgTypes, + }.Build() + File_test_proto = out.File + file_test_proto_rawDesc = nil + file_test_proto_goTypes = nil + file_test_proto_depIdxs = nil } diff --git a/benchmark/testdata/test.proto b/benchmark/testdata/test.proto index a4e1bc22..91a75374 100644 --- a/benchmark/testdata/test.proto +++ b/benchmark/testdata/test.proto @@ -1,5 +1,6 @@ syntax = "proto3"; package testdata; +option go_package = "github.com/topfreegames/pitaya/benchmark/testdata"; message Ping { string Content = 1; @@ -7,4 +8,4 @@ message Ping { message Pong { string Content = 2; -} \ No newline at end of file +} diff --git a/cmd/repl.go b/cmd/repl.go new file mode 100644 index 00000000..8940f060 --- /dev/null +++ b/cmd/repl.go @@ -0,0 +1,42 @@ +/* +Copyright © 2021 Wildlife Studios + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "github.com/spf13/cobra" + "github.com/topfreegames/pitaya/v3/repl" +) + +var docsRoute string +var fileName string +var prettyJSON bool + +// replCmd opens pitaya REPL tool +var replCmd = &cobra.Command{ + Use: "repl", + Short: "starts pitaya repl tool", + Long: `starts pitaya repl tool`, + Run: func(cmd *cobra.Command, args []string) { + repl.Start(docsRoute, fileName, prettyJSON) + }, +} + +func init() { + replCmd.Flags().StringVarP(&docsRoute, "docs", "d", "", "route containing the documentation") + replCmd.Flags().StringVarP(&fileName, "filename", "f", "", "file containing the commands to run") + replCmd.Flags().BoolVarP(&prettyJSON, "pretty", "p", false, "print pretty jsons") + rootCmd.AddCommand(replCmd) +} diff --git a/cmd/root.go b/cmd/root.go new file mode 100644 index 00000000..c5afaf6b --- /dev/null +++ b/cmd/root.go @@ -0,0 +1,41 @@ +/* +Copyright © 2021 Wildlife Studios + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "github.com/spf13/cobra" +) + +var cfgFile string + +// rootCmd represents the base command when called without any subcommands +var rootCmd = &cobra.Command{ + Use: "pitaya", + Short: "run pitaya in sidecar mode", + Long: `run pitaya in sidecar mode`, + // Uncomment the following line if your bare application + // has an action associated with it: + // Run: func(cmd *cobra.Command, args []string) { }, +} + +// Execute adds all child commands to the root command and sets flags appropriately. +// This is called by main.main(). It only needs to happen once to the rootCmd. +func Execute() { + cobra.CheckErr(rootCmd.Execute()) +} + +func init() { +} diff --git a/cmd/sidecar.go b/cmd/sidecar.go new file mode 100644 index 00000000..fac22758 --- /dev/null +++ b/cmd/sidecar.go @@ -0,0 +1,46 @@ +/* +Copyright © 2021 Wildlife Studios + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package cmd + +import ( + "github.com/spf13/cobra" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/sidecar" +) + +var sidecarConfig *config.SidecarConfig + +// sidecarCmd represents the start command +var sidecarCmd = &cobra.Command{ + Use: "sidecar", + Short: "starts pitaya in sidecar mode", + Long: `starts pitaya in sidecar mode`, + Run: func(cmd *cobra.Command, args []string) { + sc := sidecar.NewSidecar(sidecarConfig.CallTimeout) + + pitayaConfig := config.NewDefaultBuilderConfig() + server := sidecar.NewServer(sc, *pitayaConfig) + + server.Start(sidecarConfig.Bind, sidecarConfig.BindProtocol) + }, +} + +func init() { + sidecarConfig = config.NewDefaultSidecarConfig() + sidecarCmd.Flags().StringVarP(&sidecarConfig.Bind, "bind", "b", sidecarConfig.Bind, "bind address of the sidecar") + sidecarCmd.Flags().StringVarP(&sidecarConfig.BindProtocol, "bindProtocol", "p", sidecarConfig.BindProtocol, "bind protocol of the sidecar") + rootCmd.AddCommand(sidecarCmd) +} diff --git a/csharp/Makefile b/csharp/Makefile new file mode 100644 index 00000000..86bdd7cb --- /dev/null +++ b/csharp/Makefile @@ -0,0 +1,12 @@ +start-test-deps: + @docker-compose up -d + +stop-test-deps: + @docker-compose down + +test: start-test-deps + @dotnet test NPitaya.Tests + @$(MAKE) stop-test-deps + +build: + @dotnet build NPitaya --configuration Release diff --git a/csharp/NPitaya.Tests/Metric/Prometheus.cs b/csharp/NPitaya.Tests/Metric/Prometheus.cs new file mode 100644 index 00000000..3e71638c --- /dev/null +++ b/csharp/NPitaya.Tests/Metric/Prometheus.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using NPitaya.Metrics; +using Xunit; + +namespace NPitayaTest.Tests.Metric +{ + public class Prometheus + { + [Fact] + public void Can_Report_Pitaya_Metrics() + { + var cm = new CustomMetricsSpec(); + cm.Counters.Add(new CustomCounter() { Subsystem = "subsystem", Name = "nameC", Help = "help"}); + cm.Gauges.Add(new CustomGauge() { Subsystem = "subsystem", Name = "nameG", Help = "help"}); + cm.Summaries.Add(new CustomSummary() { Subsystem = "subsystem", Name = "nameS", Help = "help", Objectives = null}); + var prometheusMR = new PrometheusMetricsReporter("default", "game", 9090, null, null, cm); + MetricsReporters.AddMetricReporter(prometheusMR); + + for (var i = 0; i < 5; ++i) + { + new Thread(() => + { + Thread.CurrentThread.IsBackground = true; + + MetricsReporters.ReportTimer("success", "game.remoteGame.test", "rpc", "", Stopwatch.StartNew()); + MetricsReporters.ReportMessageProccessDelay("game.remoteGame.test", "rpc", Stopwatch.StartNew()); + MetricsReporters.ReportNumberOfConnectedClients(1); + MetricsReporters.ReportSummary("nameS", new Dictionary(), 1); + MetricsReporters.ReportGauge("nameG", new Dictionary(), 1); + MetricsReporters.ReportCount("nameC", new Dictionary(), 1); + }).Start(); + } + } + } +} \ No newline at end of file diff --git a/csharp/NPitaya.Tests/Metric/StatsDataDog.cs b/csharp/NPitaya.Tests/Metric/StatsDataDog.cs new file mode 100644 index 00000000..8ad6cee6 --- /dev/null +++ b/csharp/NPitaya.Tests/Metric/StatsDataDog.cs @@ -0,0 +1,33 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using NPitaya.Metrics; +using Xunit; + +namespace NPitayaTest.Tests.Metric +{ + public class StatsDataDog + { + [Fact] + public void Can_Report_Pitaya_Metrics() + { + var statsdMR = new StatsdMetricsReporter("localhost", 5000, "game"); + MetricsReporters.AddMetricReporter(statsdMR); + + for (var i = 0; i < 5; ++i) + { + new Thread(() => + { + Thread.CurrentThread.IsBackground = true; + + MetricsReporters.ReportTimer("success", "game.remoteGame.test", "rpc", "", Stopwatch.StartNew()); + MetricsReporters.ReportMessageProccessDelay("game.remoteGame.test", "rpc", Stopwatch.StartNew()); + MetricsReporters.ReportNumberOfConnectedClients(1); + MetricsReporters.ReportSummary("nameS", new Dictionary(), 1); + MetricsReporters.ReportGauge("nameG", new Dictionary(), 1); + MetricsReporters.ReportCount("nameC", new Dictionary(), 1); + }).Start(); + } + } + } +} \ No newline at end of file diff --git a/csharp/NPitaya.Tests/Models/PitayaConfiguration.cs b/csharp/NPitaya.Tests/Models/PitayaConfiguration.cs new file mode 100644 index 00000000..cf801413 --- /dev/null +++ b/csharp/NPitaya.Tests/Models/PitayaConfiguration.cs @@ -0,0 +1,55 @@ +using System.Text; +using NPitaya.Models; +using Xunit; + +namespace NPitayaTest.Tests.Models +{ + public class PitayaConfigurationTests + { + [Fact] + public void Pitaya_Config_Instance_Is_Not_Null() + { + Assert.NotNull(PitayaConfiguration.Config); + } + + [Fact] + public void Pitaya_Config_Contains_Default_Values() + { + var config = new PitayaConfiguration(); + foreach(var kv in config.defaultValues){ + Assert.Equal(config.defaultValues[kv.Key], config.get(kv.Key)); + } + } + + [Fact] + public void Pitaya_Config_Get_Set_Int() + { + var config = new PitayaConfiguration(); + config.putInt("Test", 1); + Assert.Equal(config.getInt("Test"), 1); + config.putInt("Test2", 0); + Assert.Equal(config.getInt("Test2"), 0); + } + + [Fact] + public void Pitaya_Config_Get_Set_String() + { + var config = new PitayaConfiguration(); + config.putString("Test3", "bla"); + Assert.Equal(config.getString("Test3"), "bla"); + config.putString("Test4", ""); + Assert.Equal(config.getString("Test4"), ""); + } + + [Fact] + public void Pitaya_Config_With_Env_Var() + { + var configKey = "test.var"; + System.Environment.SetEnvironmentVariable(configKey.ToUpper().Replace(".","_"), "3000"); + var config = new PitayaConfiguration(new System.Collections.Generic.Dictionary{ + {configKey, 1} + }); + Assert.Equal(config.getInt(configKey), 3000); + } + } +} \ No newline at end of file diff --git a/csharp/NPitaya.Tests/NPitaya.Tests.csproj b/csharp/NPitaya.Tests/NPitaya.Tests.csproj new file mode 100644 index 00000000..f731e183 --- /dev/null +++ b/csharp/NPitaya.Tests/NPitaya.Tests.csproj @@ -0,0 +1,37 @@ + + + + netcoreapp3 + + false + + NPitayaTest + + + + + + + + + + + + + + + libpitaya_cluster.bundle + + + libpitaya_cluster.dylib + + + libpitaya_cluster.so + + + + + + + + diff --git a/csharp/NPitaya.Tests/Tests/Integration/NatsCluster.cs b/csharp/NPitaya.Tests/Tests/Integration/NatsCluster.cs new file mode 100644 index 00000000..c672e518 --- /dev/null +++ b/csharp/NPitaya.Tests/Tests/Integration/NatsCluster.cs @@ -0,0 +1,95 @@ +//using System; +//using System.Collections.Generic; +//using System.Threading; +//using NPitaya; +//using NPitaya.Metrics; +//using Xunit; +// +//namespace NPitayaTest.Tests.Integration +//{ +// public class NatsCluster +// { +// [Fact] +// public void Can_Fail_Initialization_Multiple_Times() +// { +// var natsConfig = new NatsConfig( +// endpoint: "http://127.0.0.1:4222", +// connectionTimeoutMs: 1000, +// requestTimeoutMs: 5000, +// serverShutdownDeadlineMs: 10 * 1000, +// serverMaxNumberOfRpcs: int.MaxValue, +// maxConnectionRetries: 3, +// maxPendingMessages: 100); +// +// var sdCfg = new SDConfig( +// endpoints: "127.0.0.1:123123123", +// etcdPrefix: "pitaya/", +// serverTypeFilters: new List(), +// heartbeatTTLSec: 10, +// logHeartbeat: false, +// logServerSync: false, +// logServerDetails: false, +// syncServersIntervalSec: 10, +// maxNumberOfRetries: 0 +// ); +// +// var server = new Server( +// id: "id", +// type: "type", +// metadata: "", +// hostname: "", +// frontend: false +// ); +// +// for (var i = 0; i < 10; ++i) +// { +// Assert.Throws(() => +// { +// PitayaCluster.Initialize(natsConfig, sdCfg, server, NativeLogLevel.Debug); +// }); +// } +// +// PitayaCluster.Terminate(); +// } +// +// [Fact] +// public void Can_Be_Initialized_And_Terminated_Multiple_Times() +// { +// var natsConfig = new NatsConfig( +// endpoint: "http://127.0.0.1:4222", +// connectionTimeoutMs: 1000, +// requestTimeoutMs: 5000, +// serverShutdownDeadlineMs: 10 * 1000, +// serverMaxNumberOfRpcs: int.MaxValue, +// maxConnectionRetries: 3, +// maxPendingMessages: 100); +// +// var sdCfg = new SDConfig( +// endpoints: "http://127.0.0.1:2379", +// etcdPrefix: "pitaya/", +// serverTypeFilters: new List(), +// heartbeatTTLSec: 10, +// logHeartbeat: false, +// logServerSync: false, +// logServerDetails: false, +// syncServersIntervalSec: 10, +// maxNumberOfRetries: 0 +// ); +// +// var server = new Server( +// id: "myserverid", +// type: "myservertype", +// metadata: "", +// hostname: "", +// frontend: false +// ); +// +// for (var i = 0; i < 2; ++i) +// { +// PitayaCluster.Initialize(natsConfig, sdCfg, server, NativeLogLevel.Debug); +// PitayaCluster.Terminate(); +// } +// } +// +// } +//} \ No newline at end of file diff --git a/csharp/NPitaya.Tests/Tests/Models.cs b/csharp/NPitaya.Tests/Tests/Models.cs new file mode 100644 index 00000000..6f763d67 --- /dev/null +++ b/csharp/NPitaya.Tests/Tests/Models.cs @@ -0,0 +1,38 @@ +using System.Runtime.Serialization; + +namespace NPitayaTest.Tests +{ + [DataContract] + public class TestClass1 + { + [DataMember(Name = "arg1")] public string Arg1; + [DataMember(Name = "arg2")] public int Arg2; + [DataMember(Name = "arg3")] public TestClass2 Arg3; + + public override bool Equals(object other) + { + if (other == null || other.GetType() != typeof(TestClass1)) return false; + var otherT = (TestClass1) other; + var res = Arg1.Equals(otherT.Arg1) && Arg2 == otherT.Arg2; + if (Arg3 == null) + { + return res && otherT.Arg3 == null; + } + return res && Arg3.Equals(otherT.Arg3); + } + } + + [DataContract] + public class TestClass2 + { + [DataMember(Name = "arg3")] public string Arg3; + [DataMember(Name = "arg4")] public int Arg4; + + public override bool Equals(object other) + { + if (other == null || other.GetType() != typeof(TestClass2)) return false; + var otherT = (TestClass2) other; + return (Arg3.Equals(otherT.Arg3) && Arg4 == otherT.Arg4); + } + } +} \ No newline at end of file diff --git a/csharp/NPitaya.Tests/Tests/Serializer/JSONSerializerTests.cs b/csharp/NPitaya.Tests/Tests/Serializer/JSONSerializerTests.cs new file mode 100644 index 00000000..c2078778 --- /dev/null +++ b/csharp/NPitaya.Tests/Tests/Serializer/JSONSerializerTests.cs @@ -0,0 +1,60 @@ +using System.Text; +using NPitaya.Serializer; +using Xunit; + +namespace NPitayaTest.Tests.Serializer +{ + public class JSONSerializerTests + { + [Fact] + public void Marshal_Returns_Correct_Json() + { + var jsonSerializer = new JSONSerializer(); + var t1 = new TestClass1 + { + Arg1 = "bla", + Arg2 = 300 + }; + Assert.Equal("{\"arg1\":\"bla\",\"arg2\":300,\"arg3\":null}", Encoding.UTF8.GetString(jsonSerializer.Marshal(t1))); + } + + [Fact] + public void Marshal_Empty_Obj_Produces_Valid_Json() + { + var jsonSerializer = new JSONSerializer(); + var t1 = new TestClass1 + { + }; + Assert.Equal("{\"arg1\":null,\"arg2\":0,\"arg3\":null}", Encoding.UTF8.GetString(jsonSerializer.Marshal(t1))); + } + + [Fact] + public void Unmarshal_Produces_Valid_Result() + { + var jsonSerializer = new JSONSerializer(); + var t1 = jsonSerializer.Unmarshal(Encoding.UTF8.GetBytes("{\"arg1\":\"bla\",\"arg2\":19}"), typeof(TestClass1)); + Assert.Equal(t1, (new TestClass1 + { + Arg1 = "bla", + Arg2 = 19 + })); + } + + [Fact] + public void Unmarshal_Composite_Struct_Produces_Valid_Result() + { + var jsonSerializer = new JSONSerializer(); + var t1 = jsonSerializer.Unmarshal(Encoding.UTF8.GetBytes("{\"arg1\":\"bla\",\"arg2\":19,\"arg3\":{\"arg3\":\"ola\",\"arg4\":400}}"), typeof(TestClass1)); + Assert.Equal(new TestClass1 + { + Arg1 = "bla", + Arg2 = 19, + Arg3 = new TestClass2 + { + Arg3 = "ola", + Arg4 = 400 + } + }, t1); + } + } +} \ No newline at end of file diff --git a/csharp/NPitaya.Tests/Tests/Serializer/ProtobufSerializerTests.cs b/csharp/NPitaya.Tests/Tests/Serializer/ProtobufSerializerTests.cs new file mode 100644 index 00000000..49810657 --- /dev/null +++ b/csharp/NPitaya.Tests/Tests/Serializer/ProtobufSerializerTests.cs @@ -0,0 +1,7 @@ +namespace NPitayaTest.Tests.Serializer +{ + public class ProtobufSerializerTests + { + + } +} \ No newline at end of file diff --git a/csharp/NPitaya/NPitaya.csproj b/csharp/NPitaya/NPitaya.csproj new file mode 100644 index 00000000..8634b98a --- /dev/null +++ b/csharp/NPitaya/NPitaya.csproj @@ -0,0 +1,30 @@ + + + + + true + NPitayaSidecar + 0.1.6 + NPitayaSidecar + TFG Co + A full implementation of pitaya backend framework for .NET + 2019, TFG Co + pitaya,server,games,framework,rpc + true + net461;netstandard2.0 + pitaya + + + + + + + + + + + + + + + diff --git a/csharp/NPitaya/src/Constants/Routes.cs b/csharp/NPitaya/src/Constants/Routes.cs new file mode 100644 index 00000000..4ce273c4 --- /dev/null +++ b/csharp/NPitaya/src/Constants/Routes.cs @@ -0,0 +1,9 @@ +namespace NPitaya.Constants +{ + public class Routes + { + public static string SessionBindRoute = "sys.bindsession"; + public static string SessionPushRoute = "sys.pushsession"; + public static string SessionKickRoute = "sys.kick"; + } +} \ No newline at end of file diff --git a/csharp/NPitaya/src/Metrics/Constants.cs b/csharp/NPitaya/src/Metrics/Constants.cs new file mode 100644 index 00000000..e14d0789 --- /dev/null +++ b/csharp/NPitaya/src/Metrics/Constants.cs @@ -0,0 +1,43 @@ +using System; + +namespace NPitaya.Metrics +{ + public class Constants + { + internal static string PitayaKey = "pitaya"; + internal static string ResponseTimeMetricKey = "response_time_ns"; + internal static string ConnectedClientsMetricKey = "connected_clients"; + internal static string CountServersMetricKey = "count_servers"; + internal static string ChannelCapacityMetricKey = "channel_capacity"; + internal static string DroppedMessagesMetricKey = "dropped_messages"; + internal static string ProccessDelayMetricKey = "handler_delay_ns"; + internal static string GoroutinesMetricKey = "goroutines"; + internal static string HeapSizeMetricKey = "heapsize"; + internal static string HeapObjectsMetricKey = "heapobjects"; + internal static string WorkerJobsTotalMetricKey = "worker_jobs_total"; + internal static string WorkerJobsRetryMetricKey = "worker_jobs_retry_total"; + internal static string WorkerQueueSizeMetricKey = "worker_queue_size"; + internal static string ExceededRateLimitingMetricKey = "exceeded_rate_limiting"; + + public enum Status + { + fail, + success + } + + public class MetricNotFoundException : Exception + { + public MetricNotFoundException() + { + } + + public MetricNotFoundException(string message) : base(message) + { + } + + public MetricNotFoundException(string message, Exception inner) : base(message, inner) + { + } + } + } +} \ No newline at end of file diff --git a/csharp/NPitaya/src/Metrics/IMetricsReporter.cs b/csharp/NPitaya/src/Metrics/IMetricsReporter.cs new file mode 100644 index 00000000..a3ab76ee --- /dev/null +++ b/csharp/NPitaya/src/Metrics/IMetricsReporter.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; + +namespace NPitaya.Metrics +{ + public interface IMetricsReporter + { + void ReportCount(string metricKey, Dictionary labels, double value); + void ReportGauge(string metricKey, Dictionary labels, double value); + void ReportSummary(string metricKey, Dictionary labels, double value); + } +} \ No newline at end of file diff --git a/csharp/NPitaya/src/Metrics/MetricsReporters.cs b/csharp/NPitaya/src/Metrics/MetricsReporters.cs new file mode 100644 index 00000000..65671df7 --- /dev/null +++ b/csharp/NPitaya/src/Metrics/MetricsReporters.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +using System.Diagnostics; + +namespace NPitaya.Metrics +{ + public static class MetricsReporters + { + private static List _reporters = new List(); + + public static void AddMetricReporter(IMetricsReporter mr) + { + _reporters.Add(mr); + } + + public static void Terminate() + { + _reporters = new List(); + } + + public static void ReportMessageProccessDelay(string route, string type, Stopwatch sw) + { + var tags = new Dictionary { {"route", route}, {"type", type} }; + ReportSummary(Constants.ProccessDelayMetricKey, tags, sw.Elapsed.TotalMilliseconds * 1000000); + } + + public static void ReportTimer(string status, string route, string type, string code, Stopwatch sw) + { + var tags = new Dictionary { {"status", status}, {"route", route}, {"type", type}, {"code", code} }; + ReportSummary(Constants.ResponseTimeMetricKey, tags, sw.Elapsed.TotalMilliseconds * 1000000); + } + + public static void ReportNumberOfConnectedClients(double value) + { + ReportGauge(Constants.ConnectedClientsMetricKey, new Dictionary(), value); + } + + public static void ReportCount(string key, Dictionary tags, double value) + { + foreach (var reporter in _reporters) + { + reporter.ReportCount(key, tags, value); + } + } + public static void ReportGauge(string key, Dictionary tags, double value) + { + foreach (var reporter in _reporters) + { + reporter.ReportGauge(key, tags, value); + } + } + + public static void ReportSummary(string key, Dictionary tags, double value) + { + foreach (var reporter in _reporters) + { + reporter.ReportSummary(key, tags, value); + } + } + + } +} \ No newline at end of file diff --git a/csharp/NPitaya/src/Metrics/PrometheusMetricsReporter.cs b/csharp/NPitaya/src/Metrics/PrometheusMetricsReporter.cs new file mode 100644 index 00000000..a193c6ea --- /dev/null +++ b/csharp/NPitaya/src/Metrics/PrometheusMetricsReporter.cs @@ -0,0 +1,299 @@ +using System.Collections.Generic; +using System.Linq; +using Prometheus; + +namespace NPitaya.Metrics +{ + public class CustomMetricsSpec + { + public List Summaries = new List(); + public List Gauges = new List(); + public List Counters = new List(); + } + + public class CustomSummary + { + public string Subsystem; + public string Name; + public string Help; + public Dictionary Objectives = new Dictionary(); + public List Labels = new List(); + } + + public class CustomGauge + { + public string Subsystem; + public string Name; + public string Help; + public List Labels = new List(); + } + + public class CustomCounter + { + public string Subsystem; + public string Name; + public string Help; + public List Labels = new List(); + } + public class PrometheusMetricsReporter: IMetricsReporter + { + private Dictionary _additionalLabels; + private Dictionary _constantLabels; + private Dictionary _countReportersMap; + private Dictionary _summaryReportersMap; + private Dictionary _gaugeReportersMap; + + public PrometheusMetricsReporter(string serverType, string game, int port, Dictionary constantLabels = null, Dictionary additionalLabels = null, CustomMetricsSpec customMetricsSpec = null) + { + _constantLabels = constantLabels ?? new Dictionary(); + _constantLabels["game"] = game; + _constantLabels["serverType"] = serverType; + _additionalLabels = additionalLabels ?? new Dictionary(); + _countReportersMap = new Dictionary(); + _summaryReportersMap = new Dictionary(); + _gaugeReportersMap = new Dictionary(); + + if (customMetricsSpec != null) + { + _registerCustomMetrics(customMetricsSpec); + } + + _registerMetrics(); + + var prometheusServer = new MetricServer(port: port); + prometheusServer.Start(); + } + + private void _registerCustomMetrics(CustomMetricsSpec customMetricsSpec) + { + foreach (var summary in customMetricsSpec.Summaries) + { + _addSummaryReporter( + Constants.PitayaKey, + summary.Subsystem, + summary.Name, + summary.Help, + summary.Labels.ToArray(), + summary.Objectives); + } + + foreach (var gauge in customMetricsSpec.Gauges) + { + _addGaugeReporter( + Constants.PitayaKey, + gauge.Subsystem, + gauge.Name, + gauge.Help, + gauge.Labels.ToArray()); + } + + foreach (var counter in customMetricsSpec.Counters) + { + _addCounterReporter( + Constants.PitayaKey, + counter.Subsystem, + counter.Name, + counter.Help, + counter.Labels.ToArray()); + } + } + + private void _registerMetrics() + { + _addSummaryReporter( + Constants.PitayaKey, + "handler", + Constants.ResponseTimeMetricKey, + "the time to process a msg in nanoseconds", + new[]{"route", "status", "type", "code"}); + + _addSummaryReporter( + Constants.PitayaKey, + "handler", + Constants.ProccessDelayMetricKey, + "the delay to start processing a msg in nanoseconds", + new[]{"route", "type"}); + + _addGaugeReporter( + Constants.PitayaKey, + "acceptor", + Constants.ConnectedClientsMetricKey, + "the number of clients connected right now", + new string[]{}); + + _addGaugeReporter( + Constants.PitayaKey, + "service_discovery", + Constants.CountServersMetricKey, + "the number of discovered servers by service discovery", + new[]{"type"}); + + _addGaugeReporter( + Constants.PitayaKey, + "channel", + Constants.ChannelCapacityMetricKey, + "the available capacity of the channel", + new[]{"channel"}); + + _addGaugeReporter( + Constants.PitayaKey, + "rpc_server", + Constants.DroppedMessagesMetricKey, + "the number of rpc server dropped messages (messages that are not handled)", + new string[]{}); + + _addGaugeReporter( + Constants.PitayaKey, + "sys", + Constants.GoroutinesMetricKey, + "the current number of goroutines", + new string[]{}); + + _addGaugeReporter( + Constants.PitayaKey, + "sys", + Constants.HeapSizeMetricKey, + "the current heap size", + new string[]{}); + + _addGaugeReporter( + Constants.PitayaKey, + "sys", + Constants.HeapObjectsMetricKey, + "the current number of allocated heap objects", + new string[]{}); + + _addGaugeReporter( + Constants.PitayaKey, + "worker", + Constants.WorkerJobsRetryMetricKey, + "the current number of job retries", + new string[]{}); + + _addGaugeReporter( + Constants.PitayaKey, + "worker", + Constants.WorkerQueueSizeMetricKey, + "the current queue size", + new[]{"queue"}); + + _addGaugeReporter( + Constants.PitayaKey, + "worker", + Constants.WorkerJobsTotalMetricKey, + "the total executed jobs", + new[]{"status"}); + + _addCounterReporter( + Constants.PitayaKey, + "acceptor", + Constants.ExceededRateLimitingMetricKey, + "the number of blocked requests by exceeded rate limiting", + new string[]{}); + } + + private void _addSummaryReporter(string metricNamespace, string metricSubsystem, string metricName, string metricHelp, string[] metricLabels, Dictionary objectives = null) + { + var allLabels = new List(); + allLabels.AddRange(_constantLabels.Keys.ToArray()); + allLabels.AddRange(_additionalLabels.Keys.ToArray()); + allLabels.AddRange(metricLabels); + var summaryObjectives = new List(); + if (objectives != null) + { + foreach (var kv in objectives) + { + summaryObjectives.Add(new QuantileEpsilonPair(kv.Key, kv.Value)); + } + } + else + { + summaryObjectives.Add(new QuantileEpsilonPair(0.7, 0.02)); + summaryObjectives.Add(new QuantileEpsilonPair(0.95, 0.005)); + summaryObjectives.Add(new QuantileEpsilonPair(0.99, 0.001)); + } + + + var summary = Prometheus.Metrics.CreateSummary(metricNamespace + "_" + metricSubsystem + "_" + metricName, metricHelp, new SummaryConfiguration + { + Objectives = summaryObjectives, + LabelNames = allLabels.ToArray(), + }); + _summaryReportersMap[metricName] = summary; + } + + private void _addCounterReporter(string metricNamespace, string metricSubsystem, string metricName, string metricHelp, string[] metricLabels) + { + var allLabels = new List(); + allLabels.AddRange(_constantLabels.Keys.ToArray()); + allLabels.AddRange(_additionalLabels.Keys.ToArray()); + allLabels.AddRange(metricLabels); + var counter = Prometheus.Metrics.CreateCounter(metricNamespace + "_" + metricSubsystem + "_" + metricName, metricHelp, new CounterConfiguration + { + LabelNames = allLabels.ToArray(), + }); + _countReportersMap[metricName] = counter; + } + + private void _addGaugeReporter(string metricNamespace, string metricSubsystem, string metricName, string metricHelp, string[] metricLabels) + { + var allLabels = new List(); + allLabels.AddRange(_constantLabels.Keys.ToArray()); + allLabels.AddRange(_additionalLabels.Keys.ToArray()); + allLabels.AddRange(metricLabels); + var gauge = Prometheus.Metrics.CreateGauge(metricNamespace + "_" + metricSubsystem + "_" + metricName, metricHelp, new GaugeConfiguration + { + LabelNames = allLabels.ToArray(), + }); + _gaugeReportersMap[metricName] = gauge; + } + + public void ReportCount(string metricKey, Dictionary tags, double value) + { + if (!_countReportersMap.TryGetValue(metricKey, out var counter)) return; + var labelValues = _ensureLabels(tags, counter.LabelNames); + counter.WithLabels(labelValues).Inc(value); + } + + public void ReportGauge(string metricKey, Dictionary tags, double value) + { + if (!_gaugeReportersMap.TryGetValue(metricKey, out var gauge)) return; + var labelValues = _ensureLabels(tags, gauge.LabelNames); + gauge.WithLabels(labelValues).Set(value); + } + + public void ReportSummary(string metricKey, Dictionary tags, double value) + { + if (!_summaryReportersMap.TryGetValue(metricKey, out var summary)) return; + var labelValues = _ensureLabels(tags, summary.LabelNames); + summary.WithLabels(labelValues).Observe(value); + } + + private string[] _ensureLabels(Dictionary labels, string[] labelNames) + { + var labelValues = new List(); + foreach (var lName in labelNames) + { + if (labels.TryGetValue(lName, out var lValue)) + { + labelValues.Add(lValue); + continue; + } + if (_additionalLabels.TryGetValue(lName, out lValue)) + { + labelValues.Add(lValue); + continue; + } + if (_constantLabels.TryGetValue(lName, out lValue)) + { + labelValues.Add(lValue); + continue; + } + + labelValues.Add(""); + } + + return labelValues.ToArray(); + } + } +} \ No newline at end of file diff --git a/csharp/NPitaya/src/Metrics/StatsdMetricsReporter.cs b/csharp/NPitaya/src/Metrics/StatsdMetricsReporter.cs new file mode 100644 index 00000000..5d819b5d --- /dev/null +++ b/csharp/NPitaya/src/Metrics/StatsdMetricsReporter.cs @@ -0,0 +1,54 @@ +using System.Collections.Generic; +using StatsdClient; + +namespace NPitaya.Metrics +{ + public class StatsdMetricsReporter: IMetricsReporter + { + public StatsdMetricsReporter(string statsdHost, int statsdPort, string metricsPrefix, Dictionary constantTags = null) + { + var parsedTags = _dictTagsToStringSlice(constantTags); + StatsdConfig statsdConfig = new StatsdConfig + { + StatsdServerName = statsdHost, + StatsdPort = statsdPort, + Prefix = metricsPrefix.TrimEnd('.'), + ConstantTags = parsedTags + }; + DogStatsd.Configure(statsdConfig); + } + + private static string[] _dictTagsToStringSlice(Dictionary dictTags) + { + if (dictTags is null) + { + return new string[0]; + } + var res = new string[dictTags.Count]; + var i = 0; + foreach (KeyValuePair kv in dictTags) + { + res[i++] = $"{kv.Key}:{kv.Value}"; + } + + return res; + } + + public void ReportCount(string metricKey, Dictionary tags, double value) + { + var parsedTags = _dictTagsToStringSlice(tags); + DogStatsd.Counter(metricKey, value, tags:parsedTags); + } + + public void ReportGauge(string metricKey, Dictionary tags, double value) + { + var parsedTags = _dictTagsToStringSlice(tags); + DogStatsd.Gauge(metricKey, value, tags:parsedTags); + } + public void ReportSummary(string metricKey, Dictionary tags, double value) + { + var parsedTags = _dictTagsToStringSlice(tags); + DogStatsd.Timer(metricKey, value, tags:parsedTags); + } + } +} \ No newline at end of file diff --git a/csharp/NPitaya/src/Models/BaseHandler.cs b/csharp/NPitaya/src/Models/BaseHandler.cs new file mode 100644 index 00000000..e3763e93 --- /dev/null +++ b/csharp/NPitaya/src/Models/BaseHandler.cs @@ -0,0 +1,55 @@ +using System.Reflection; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace NPitaya.Models +{ + public class BaseHandler : IRemote + { + public string GetName() + { + return GetType().Name; + } + + public Dictionary GetRemotesMap() + { + Dictionary dict = new Dictionary(); + MethodBase[] methods = this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public); + foreach (var methodBase in methods) + { + var m = (MethodInfo) methodBase; + if (m.IsPublic) + { + if (typeof(Task).IsAssignableFrom(m.ReturnType)) + { + var returnType = m.ReturnType.GenericTypeArguments.Length > 0 + ? m.ReturnType.GenericTypeArguments[0] + : typeof(void); + ParameterInfo[] parameters = m.GetParameters(); + if (parameters.Length == 2) // TODO need to use context + { + if (typeof(PitayaSession) == + parameters[0].ParameterType && // TODO support bytes in and out, support context + (typeof(object).IsAssignableFrom(parameters[1].ParameterType))) + { + dict[m.Name] = new RemoteMethod(this, m, returnType, parameters[1].ParameterType); + } + } + + if (parameters.Length == 1 && typeof(PitayaSession) == parameters[0].ParameterType) + { + dict[m.Name] = new RemoteMethod(this, m, returnType, null); + } + } + } + } + + return dict; + } + + private static bool isValidHandler() + { + return true; //TODO implement this + } + } +} diff --git a/csharp/NPitaya/src/Models/BaseRemote.cs b/csharp/NPitaya/src/Models/BaseRemote.cs new file mode 100644 index 00000000..30bdf438 --- /dev/null +++ b/csharp/NPitaya/src/Models/BaseRemote.cs @@ -0,0 +1,50 @@ +using System.Reflection; +using Google.Protobuf; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace NPitaya.Models +{ + public class BaseRemote : IRemote + { + public string GetName() + { + return GetType().Name; + } + + public Dictionary GetRemotesMap() + { + Dictionary dict = new Dictionary(); + MethodBase[] methods = GetType().GetMethods(BindingFlags.Instance | + BindingFlags.Public); + foreach (MethodInfo m in methods) + { + if (m.IsPublic) + { + if (typeof(Task).IsAssignableFrom(m.ReturnType)) + { + var returnType = m.ReturnType.GenericTypeArguments.Length > 0 + ? m.ReturnType.GenericTypeArguments[0] + : typeof(void); + ParameterInfo[] parameters = m.GetParameters(); + if (parameters.Length == 1) + { + if (typeof(object).IsAssignableFrom(parameters[0].ParameterType)) + { + dict[m.Name] = new RemoteMethod(this, m, returnType, + parameters[0].ParameterType); + } + } + } + } + } + + return dict; + } + + private static bool isValidRemote() + { + return true; + } + } +} diff --git a/csharp/NPitaya/src/Models/IRemote.cs b/csharp/NPitaya/src/Models/IRemote.cs new file mode 100644 index 00000000..4c6b6831 --- /dev/null +++ b/csharp/NPitaya/src/Models/IRemote.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using NPitaya; + +namespace NPitaya.Models +{ + public interface IRemote + { + string GetName(); + Dictionary GetRemotesMap(); + } +} diff --git a/csharp/NPitaya/src/Models/Logger.cs b/csharp/NPitaya/src/Models/Logger.cs new file mode 100644 index 00000000..11dbef17 --- /dev/null +++ b/csharp/NPitaya/src/Models/Logger.cs @@ -0,0 +1,49 @@ +using System; + +namespace NPitaya.Models{ + public enum LogLevel{ + ERROR=0, + WARNING=1, + INFO=2, + DEBUG=3 + } + + public static class Logger{ + private static LogLevel level = LogLevel.INFO; + public delegate void LogDelegate(LogLevel level, string logMsg, params object[] modifiers); + public static LogDelegate LogFunc = new LogDelegate(log); + + private static void log(LogLevel logLevel, string logMsg, params object[] modifiers){ + if (level >= logLevel){ + #if UNITY_STANDALONE || UNITY_EDITOR + UnityEngine.Debug.Log("[" + logLevel.ToString().ToUpper() + "] " + logMsg); + #else + Console.WriteLine("[" + logLevel.ToString().ToUpper() + "] " + logMsg, modifiers); + #endif + } + } + + public static void SetLevel(LogLevel logLevel){ + level = logLevel; + } + + public static void Error(string logMsg, params object[] modifiers){ + LogFunc(LogLevel.ERROR, logMsg, modifiers); + } + + public static void Warn(string logMsg, params object[] modifiers) + { + LogFunc(LogLevel.WARNING, logMsg, modifiers); + } + public static void Info(string logMsg, params object[] modifiers) + { + LogFunc(LogLevel.INFO, logMsg, modifiers); + } + + public static void Debug(string logMsg, params object[] modifiers) + { + LogFunc(LogLevel.DEBUG, logMsg, modifiers); + } + + } +} diff --git a/csharp/NPitaya/src/Models/PitayaConfiguration.cs b/csharp/NPitaya/src/Models/PitayaConfiguration.cs new file mode 100644 index 00000000..ecc222c0 --- /dev/null +++ b/csharp/NPitaya/src/Models/PitayaConfiguration.cs @@ -0,0 +1,98 @@ +using System.Collections.Generic; + + +namespace NPitaya.Models +{ + public class PitayaConfiguration + { + public const string CONFIG_HEARTBEAT_TIMEOUT_MS = "pitaya.sidecar.heartbeattimeoutms"; + public const string CONFIG_READBUFFER_SIZE = "pitaya.sidecar.readbuffersize"; + public const string CONFIG_WRITEBUFFER_SIZE = "pitaya.sidecar.writebuffersize"; + + public static Dictionary DefaultValues = new Dictionary{ + {CONFIG_HEARTBEAT_TIMEOUT_MS, 5000}, + {CONFIG_READBUFFER_SIZE, 1000}, + {CONFIG_WRITEBUFFER_SIZE, 1000}, + }; + + public Dictionary defaultValues; + private readonly Dictionary configMap = new Dictionary(); + + public static PitayaConfiguration Config; + + private void initializeDefaultConfigurations(){ + foreach (var kv in defaultValues){ + configMap[kv.Key] = kv.Value; + } + } + + private string configNameToEnvVar(string configName){ + return configName.ToUpper().Replace(".", "_"); + } + + private void replaceConfigWithEnv(){ + foreach (var kv in defaultValues) + { + var envVarValue = System.Environment.GetEnvironmentVariable(configNameToEnvVar(kv.Key)); + if (envVarValue != null){ + if(int.TryParse(kv.Value.ToString(), out var intVal)){ + if (int.TryParse(envVarValue, out var ret)){ + configMap[kv.Key] = ret; + } else { + Logger.Error("Tried to set int configuration: {0} with non valid number: {1}", kv.Key, envVarValue); + } + } else { + configMap[kv.Key] = envVarValue; + } + } + } + } + + static PitayaConfiguration() { + if (Config == null){ + Config = new PitayaConfiguration(); + } + } + + public PitayaConfiguration(Dictionary defaultValues){ + this.defaultValues = defaultValues; + initializeDefaultConfigurations(); + replaceConfigWithEnv(); + } + + public PitayaConfiguration(){ + defaultValues = DefaultValues; + initializeDefaultConfigurations(); + replaceConfigWithEnv(); + } + + public string getString(string key){ + return configMap[key].ToString(); + } + + public object get(string key){ + return configMap[key]; + } + + public int getInt(string key){ + int.TryParse(configMap[key].ToString(), out var ret); + return ret; + } + + public void putInt(string key, int value){ + configMap[key] = value; + } + + public void putString(string key, string value){ + configMap[key] = value; + } + + public void reset(){ + configMap.Clear(); + initializeDefaultConfigurations(); + replaceConfigWithEnv(); + } + + } + +} \ No newline at end of file diff --git a/csharp/NPitaya/src/Models/PitayaSession.cs b/csharp/NPitaya/src/Models/PitayaSession.cs new file mode 100644 index 00000000..d7c921f8 --- /dev/null +++ b/csharp/NPitaya/src/Models/PitayaSession.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Google.Protobuf; +using NPitaya.Constants; +using Json = PitayaSimpleJson.SimpleJson; +using NPitaya.Protos; + +namespace NPitaya.Models +{ + public class PitayaSession + { + private Int64 _id; + private string _frontendId; + private Dictionary _data; + private string _rawData; + public string RawData => _rawData; + public string Uid { get; private set; } + + public PitayaSession(Protos.Session sessionProto) + { + _id = sessionProto.Id; + Uid = sessionProto.Uid; + _rawData = sessionProto.Data.ToStringUtf8(); + if (!String.IsNullOrEmpty(_rawData)) + _data = Json.DeserializeObject>(_rawData); + } + + public PitayaSession(Protos.Session sessionProto, string frontendId):this(sessionProto) + { + _frontendId = frontendId; + } + + public override string ToString() + { + return $"ID: {_id}, UID: {Uid}, Data: {_rawData}"; + } + + public void Set(string key, object value) + { + _data[key] = value; + _rawData = Json.SerializeObject(_data); + } + + public object GetObject(string key) + { + if (!_data.ContainsKey(key)) + { + throw new Exception($"key not found in session, parameter: {key}"); + } + + return _data[key]; + } + + public string GetString(string key) + { + return GetObject(key) as string; + } + + public int GetInt(string key) + { + var obj = GetObject(key); + return obj is int ? (int) obj : 0; + } + + public double GetDouble(string key) + { + var obj = GetObject(key); + return obj is double ? (double) obj : 0; + } + + public Task PushToFrontend() + { + if (String.IsNullOrEmpty(_frontendId)) + { + return Task.FromException(new Exception("cannot push to frontend, frontendId is invalid!")); + } + return SendRequestToFront(Routes.SessionPushRoute, true); + } + + public Task Bind(string uid) + { + if (Uid != "") + { + return Task.FromException(new Exception("session already bound!")); + } + Uid = uid; + // TODO only if server type is backend + // TODO bind callbacks + if (!string.IsNullOrEmpty(_frontendId)){ + return BindInFrontend(); + } + + return Task.CompletedTask; + } + + private Task BindInFrontend() + { + return SendRequestToFront(Routes.SessionBindRoute, false); + } + + private Task SendRequestToFront(string route, bool includeData) + { + var sessionProto = new Protos.Session + { + Id = _id, + Uid = Uid + }; + if (includeData) + { + sessionProto.Data = ByteString.CopyFromUtf8(_rawData); + } + return PitayaCluster.Rpc(_frontendId, Route.FromString(route), sessionProto.ToByteArray()); + } + + public Task Push(object pushMsg, string svType, string route) + { + return PitayaCluster.SendPushToUser(svType, route, Uid, pushMsg); + } + + public Task Kick(string svType) + { + return PitayaCluster.SendKickToUser(svType, new KickMsg + { + UserId = Uid + }); + } + } +} diff --git a/csharp/NPitaya/src/Models/Remote.cs b/csharp/NPitaya/src/Models/Remote.cs new file mode 100644 index 00000000..546ed4bc --- /dev/null +++ b/csharp/NPitaya/src/Models/Remote.cs @@ -0,0 +1,18 @@ +namespace NPitaya.Models +{ + [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)] + public class Remote: System.Attribute + { + private string _name; + + public Remote(string name) + { + _name = name; + } + + public Remote() + { + _name = Utils.Utils.DefaultRemoteNameFunc(GetType().Name); + } + } +} diff --git a/csharp/NPitaya/src/Models/RemoteMethod.cs b/csharp/NPitaya/src/Models/RemoteMethod.cs new file mode 100644 index 00000000..a4f549e0 --- /dev/null +++ b/csharp/NPitaya/src/Models/RemoteMethod.cs @@ -0,0 +1,19 @@ +using System; +using System.Reflection; + +namespace NPitaya.Models +{ + public class RemoteMethod + { + public readonly IRemote Obj; + internal MethodBase Method { get; } + internal Type ReturnType { get; } + internal Type ArgType { get; } + public RemoteMethod(IRemote obj, MethodBase method, Type returnType, Type argType){ + Obj = obj; + Method = method; + ReturnType = returnType; + ArgType = argType; + } + } +} diff --git a/csharp/NPitaya/src/NativeInterop.cs b/csharp/NPitaya/src/NativeInterop.cs new file mode 100644 index 00000000..742bf06d --- /dev/null +++ b/csharp/NPitaya/src/NativeInterop.cs @@ -0,0 +1,218 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using PitayaSimpleJson; + +namespace NPitaya +{ + + [StructLayout(LayoutKind.Sequential)] + public struct CRpc + { + public IntPtr reqBufferPtr; + public IntPtr tag; + } + + [StructLayout(LayoutKind.Sequential)] + public struct Error + { + [MarshalAs(UnmanagedType.LPStr)] + public string code; + [MarshalAs(UnmanagedType.LPStr)] + public string msg; + } + + public enum NativeLogLevel + { + Debug = 0, + Info = 1, + Warn = 2, + Error = 3, + Critical = 4, + } + + [StructLayout(LayoutKind.Sequential)] + public struct SDConfig + { + [MarshalAs(UnmanagedType.LPStr)] + public string endpoints; + [MarshalAs(UnmanagedType.LPStr)] + public string etcdPrefix; + [MarshalAs(UnmanagedType.LPStr)] + public string serverTypeFiltersStr; + public int heartbeatTTLSec; + public int logHeartbeat; + public int logServerSync; + public int logServerDetails; + public int syncServersIntervalSec; + public int maxNumberOfRetries; + + public SDConfig(string endpoints, string etcdPrefix, List serverTypeFilters, int heartbeatTTLSec, bool logHeartbeat, + bool logServerSync, bool logServerDetails, int syncServersIntervalSec, int maxNumberOfRetries) + { + this.endpoints = endpoints; + this.etcdPrefix = etcdPrefix; + this.heartbeatTTLSec = heartbeatTTLSec; + this.logHeartbeat = Convert.ToInt32(logHeartbeat); + this.logServerSync = Convert.ToInt32(logServerSync); + this.logServerDetails = Convert.ToInt32(logServerDetails); + this.syncServersIntervalSec = syncServersIntervalSec; + this.maxNumberOfRetries = maxNumberOfRetries; + try + { + serverTypeFiltersStr = SimpleJson.SerializeObject(serverTypeFilters); + } + catch (Exception e) + { + throw new Exception("Failed to serialize serverTypeFilters: " + e.Message); + } + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct GrpcConfig + { + [MarshalAs(UnmanagedType.LPStr)] + public string host; + public int port; + public int serverShutdownDeadlineMs; + public int serverMaxNumberOfRpcs; + public int clientRpcTimeoutMs; + + public GrpcConfig( + string host, + int port, + int serverShutdownDeadlineMs, + int serverMaxNumberOfRpcs, + int clientRpcTimeoutMs) + { + this.host = host; + this.port = port; + this.serverShutdownDeadlineMs = serverShutdownDeadlineMs; + this.serverMaxNumberOfRpcs = serverMaxNumberOfRpcs; + this.clientRpcTimeoutMs = clientRpcTimeoutMs; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct Route + { + [MarshalAs(UnmanagedType.LPStr)] + public string svType; + [MarshalAs(UnmanagedType.LPStr)] + public string service; + [MarshalAs(UnmanagedType.LPStr)] + public string method; + + public Route(string svType, string service, string method):this(service, method) + { + this.svType = svType; + } + + public Route(string service, string method) + { + this.service = service; + this.method = method; + svType = ""; + } + + public static Route FromString(string r) + { + string[] res = r.Split(new[] { "." }, StringSplitOptions.None); + if (res.Length == 3) + { + return new Route(res[0], res[1], res[2]); + } + if (res.Length == 2) + { + return new Route(res[0], res[1]); + } + throw new Exception($"invalid route: {r}"); + } + + public override string ToString() + { + if (svType.Length > 0) + { + return $"{svType}.{service}.{method}"; + } + return $"{service}.{method}"; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct MemoryBuffer + { + public IntPtr data; + public int size; + + public byte[] GetData() + { + byte[] data = new byte[this.size]; + Marshal.Copy(this.data, data, 0, this.size); + return data; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct NatsConfig + { + [MarshalAs(UnmanagedType.LPStr)] + public string endpoint; + public Int64 connectionTimeoutMs; + public int requestTimeoutMs; + public int serverShutdownDeadlineMs; + public int serverMaxNumberOfRpcs; + public int maxConnectionRetries; + public int maxPendingMessages; + + public NatsConfig(string endpoint, + int connectionTimeoutMs, + int requestTimeoutMs, + int serverShutdownDeadlineMs, + int serverMaxNumberOfRpcs, + int maxConnectionRetries, + int maxPendingMessages) + { + this.endpoint = endpoint; + this.connectionTimeoutMs = connectionTimeoutMs; + this.requestTimeoutMs = requestTimeoutMs; + this.serverShutdownDeadlineMs = serverShutdownDeadlineMs; + this.serverMaxNumberOfRpcs = serverMaxNumberOfRpcs; + this.maxConnectionRetries = maxConnectionRetries; + this.maxPendingMessages = maxPendingMessages; + } + } +} + +class StructWrapper : IDisposable +{ + public IntPtr Ptr { get; private set; } + + public StructWrapper(object obj) + { + Ptr = Marshal.AllocHGlobal(Marshal.SizeOf(obj)); + Marshal.StructureToPtr(obj, Ptr, false); + } + + ~StructWrapper() + { + if (Ptr != IntPtr.Zero) + { + Marshal.FreeHGlobal(Ptr); + Ptr = IntPtr.Zero; + } + } + + public void Dispose() + { + Marshal.FreeHGlobal(Ptr); + Ptr = IntPtr.Zero; + GC.SuppressFinalize(this); + } + + public static implicit operator IntPtr(StructWrapper w) + { + return w.Ptr; + } +} diff --git a/csharp/NPitaya/src/PSidecarClient.cs b/csharp/NPitaya/src/PSidecarClient.cs new file mode 100644 index 00000000..62311fde --- /dev/null +++ b/csharp/NPitaya/src/PSidecarClient.cs @@ -0,0 +1,264 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using Grpc.Core; +using NPitaya.Models; +using NPitaya.Protos; +using System.Threading.Tasks; +using Google.Protobuf; +using NPitaya.Metrics; +using NPitaya.Serializer; +using static NPitaya.Utils.Utils; +using Server = NPitaya.Protos.Server; + +namespace NPitaya +{ + public partial class PitayaCluster + { + private static bool _isInitialized = false; + private static Sidecar.SidecarClient _client = null; + private static Grpc.Core.Channel _channel; + + static BlockingCollection queueRead = new BlockingCollection(PitayaConfiguration.Config.getInt(PitayaConfiguration.CONFIG_READBUFFER_SIZE)); + static BlockingCollection queueWrite = new BlockingCollection(PitayaConfiguration.Config.getInt(PitayaConfiguration.CONFIG_WRITEBUFFER_SIZE)); + + static PitayaCluster(){ + GrpcEnvironment.SetCompletionQueueCount(Environment.ProcessorCount); + GrpcEnvironment.SetThreadPoolSize(Environment.ProcessorCount); + } + + public static void InitializeSidecarClientWithPitaya(string sidecarAddr, int sidecarPort, NPitaya.Protos.Server server, bool debug = false) + { + if (_isInitialized) + { + Logger.Warn("Pitaya is already initialized!"); + return; + } + + InitializeSidecarClient(sidecarAddr, sidecarPort); + InitializePitaya(server, debug); + } + + public static void InitializeSidecarClient(string sidecarAddr, int sidecarPort) + { + if (_isInitialized) + { + Logger.Warn("Pitaya is already initialized!"); + return; + } + + if (sidecarPort != 0) + { + _channel = new Channel(sidecarAddr, sidecarPort, ChannelCredentials.Insecure); + } + else + { + _channel = new Channel(sidecarAddr, ChannelCredentials.Insecure); + } + + _client = new Sidecar.SidecarClient(_channel); + + // this is a hacky approach to detect if server is not running anymore, and if not, die + new System.Threading.Thread(async() => + { + while (!_channel.ShutdownToken.IsCancellationRequested) + { + _client.Heartbeat(new Google.Protobuf.WellKnownTypes.Empty()); + var timeoutMs = PitayaConfiguration.Config.getInt(PitayaConfiguration.CONFIG_HEARTBEAT_TIMEOUT_MS); + await Task.Delay(TimeSpan.FromMilliseconds(timeoutMs), + _channel.ShutdownToken); + } + }).Start(); + + ListenToIncomingRPCs(_client); + ListenSDEvents(_client); + + _isInitialized = true; + } + static void InitializePitaya(NPitaya.Protos.Server server, bool debug = false){ + var req = new StartPitayaRequest { Config = server, DebugLog = debug }; + _client.StartPitaya(req); + } + + private static void ListenToIncomingRPCs(Sidecar.SidecarClient client) + { + var stream = client.ListenRPC(); + + new Thread(async () =>{ + while (await stream.ResponseStream.MoveNext(_channel.ShutdownToken)) + { + var current = stream.ResponseStream.Current; + queueRead.Add(current); + } + }).Start(); + + new Thread(async () =>{ + while (true) + { + var res = queueWrite.Take(); + await stream.RequestStream.WriteAsync(res); + } + }).Start(); + + for (int i = 0; i < ProcessorsCount; i++) + { + var threadId = i + 1; + new Thread(async () => + { + Logger.Debug($"[Consumer thread {threadId}] Started"); + while (!_channel.ShutdownToken.IsCancellationRequested) + { + var req = queueRead.Take(_channel.ShutdownToken); + //#pragma warning disable 4014 + var res = await HandleIncomingRpc(req.Req); + //#pragma warning restore 4014 + queueWrite.Add(new Protos.RPCResponse { ReqId = req.ReqId, Res = res }); + } + }).Start(); + } + } + + private static void ListenSDEvents(Sidecar.SidecarClient client) + { + var stream = client.ListenSD(new Google.Protobuf.WellKnownTypes.Empty()); + new Thread(async () =>{ + while (await stream.ResponseStream.MoveNext(_channel.ShutdownToken)) + { + var current = stream.ResponseStream.Current; + if (_onSDEvent != null){ + _onSDEvent(current); + } + } + }).Start(); + } + + public static Task SendPushToUser(string serverType, string route, string uid, + object pushMsg) + { + // TODO see if this taskfactory is still required + return _rpcTaskFactory.StartNew(() => + { + var push = new Push + { + Route = route, + Uid = uid, + Data = ByteString.CopyFrom(SerializerUtils.SerializeOrRaw(pushMsg, _serializer)) + }; + + var span = _tracer.BuildSpan("system.push") + .WithTag("peer.serverType", serverType) + .Start(); + var res = _client.SendPush(new PushRequest{FrontendType=serverType, Push=push}, GRPCMetadataWithSpanContext(span)); + span.Finish(); + return res; + }); + } + + public static Task SendKickToUser(string serverType, KickMsg kick) + { + return _rpcTaskFactory.StartNew(() => + { + var span = _tracer.BuildSpan("system.kick") + .WithTag("peer.serverType", serverType) + .Start(); + var res = _client.SendKick(new KickRequest{FrontendType=serverType, Kick=kick}, GRPCMetadataWithSpanContext(span)); + span.Finish(); + return res; + }); + } + + public static Task Rpc(string serverId, Route route, object msg) + { + return _rpcTaskFactory.StartNew(() => + { + var retError = new Error(); + var ok = false; + Response res = null; + Stopwatch sw = null; + var span = _tracer.BuildSpan(route.ToString()) + .WithTag("peer.id", serverId) + .WithTag("peer.serverType", route.svType) + .Start(); + try + { + var data = SerializerUtils.SerializeOrRaw(msg, _serializer); + sw = Stopwatch.StartNew(); + // TODO this can be optimized I think by using a readonly span + res = _client.SendRPC(new RequestTo{ServerID=serverId, Msg=new Msg{Route=route.ToString(), Data=ByteString.CopyFrom(data.AsSpan()), Type=MsgType.MsgRequest}}, GRPCMetadataWithSpanContext(span)); + sw.Stop(); + var protoRet = GetProtoMessageFromResponse(res); + return protoRet; + } + finally + { + if (sw != null) + { + if (ok) + { + MetricsReporters.ReportTimer(Metrics.Constants.Status.success.ToString(), route.ToString(), + "rpc", "", sw); + } + else + { + MetricsReporters.ReportTimer(Metrics.Constants.Status.fail.ToString(), route.ToString(), + "rpc", $"{retError.code}", sw); + } + } + span.Finish(); + } + }); + } + + public static Task Rpc(Route route, object msg) + { + return Rpc("", route, msg); + } + + public static Server GetServerById(string serverId) + { + try{ + var protoSv = _client.GetServer(new NPitaya.Protos.Server{Id=serverId}); + return protoSv; + } catch (Exception){ + return null; + } + } + + // TODO find better place for this method + private static Grpc.Core.Metadata GRPCMetadataWithSpanContext(OpenTracing.ISpan span){ + var dictionary = new Dictionary(); + _tracer.Inject(span.Context, OpenTracing.Propagation.BuiltinFormats.HttpHeaders, + new OpenTracing.Propagation.TextMapInjectAdapter(dictionary)); + Grpc.Core.Metadata metadata = new Grpc.Core.Metadata(); + foreach (var kvp in dictionary) + { + metadata.Add(kvp.Key, kvp.Value); + } + return metadata; + } + + public static void ShutdownSidecar(){ + if (!_isInitialized){ + return; + } + var task = _channel.ShutdownAsync(); + task.Wait(); + _client = null; + _channel = null; + _isInitialized = false; + } + public static async Task ShutdownSidecarAsync() + { + if (!_isInitialized) { + return false; + } + await _channel.ShutdownAsync(); + _channel = null; + _client = null; + _isInitialized = false; + return true; + } + } +} diff --git a/csharp/NPitaya/src/PitayaCluster.API.cs b/csharp/NPitaya/src/PitayaCluster.API.cs new file mode 100644 index 00000000..5ff339c3 --- /dev/null +++ b/csharp/NPitaya/src/PitayaCluster.API.cs @@ -0,0 +1,256 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using NPitaya.Models; +using NPitaya.Serializer; +using NPitaya.Protos; +using NPitaya.Utils; +using static NPitaya.Utils.Utils; +using System.Linq; +using Jaeger; +using Jaeger.Samplers; +using Jaeger.Reporters; +using Jaeger.Senders.Thrift; +using Microsoft.Extensions.DependencyInjection; +using OpenTracing.Util; + +// TODO profiling +// TODO better reflection performance in task async call +// TODO support to sync methods +// TODO benchmark with blocking handlers +namespace NPitaya +{ + public partial class PitayaCluster + { + private static readonly int ProcessorsCount = Environment.ProcessorCount; + private static ISerializer _serializer = new ProtobufSerializer(); + public delegate string RemoteNameFunc(string methodName); + private delegate void OnSignalFunc(); + private static readonly Dictionary RemotesDict = new Dictionary(); + private static readonly Dictionary HandlersDict = new Dictionary(); + private static readonly LimitedConcurrencyLevelTaskScheduler Lcts = new LimitedConcurrencyLevelTaskScheduler(ProcessorsCount); + private static TaskFactory _rpcTaskFactory = new TaskFactory(Lcts); + + private static Action _onSignalEvent; + private static bool _processedSigint = false; + + private static Action _onSDEvent; + + // Tracer + private static Tracer _tracer; + + public static void Initialize(string sidecarListenSocket, + Server server = null, + Action cbServiceDiscovery = null, + IServiceProvider serviceProvider = null, + bool debug = false){ + Initialize(sidecarListenSocket, 0, server, cbServiceDiscovery, serviceProvider, debug); + } + + public static void Initialize(string sidecarAddr, + int sidecarPort, + Server server = null, + Action cbServiceDiscovery = null, + IServiceProvider serviceProvider = null, + bool debug = false){ + if (_isInitialized){ + Logger.Warn("Initialize called but pitaya is already initialized"); + return; + } + + if (server != null) + { + InitializeSidecarClientWithPitaya(sidecarAddr, sidecarPort, server, debug); + } + else + { + InitializeSidecarClient(sidecarAddr, sidecarPort); + } + + InitializeInternal(cbServiceDiscovery, serviceProvider); + } + + static void InitializeInternal(Action cbServiceDiscovery, IServiceProvider serviceProvider){ + if (_client == null) + { + throw new PitayaException("Initialization failed"); + } + + RegisterRemotesAndHandlers(serviceProvider); + + SetServiceDiscoveryListener(cbServiceDiscovery); + RegisterGracefulShutdown(); + } + + // TODO this should now be a pure csharp implementation of getting sigint/sigterm + public static void AddSignalHandler(Action cb) + { + _onSignalEvent += cb; + } + + private static void OnSignal() + { + Logger.Info("Invoking signal handler"); + _onSignalEvent?.Invoke(); + } + + private static List GetAllInheriting(Type type) + { + return AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()) + .Where(x => type.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract && x.FullName != type.FullName) + .Select(x => x).ToList(); + } + + + private static void RegisterRemotesAndHandlers(IServiceProvider serviceProvider){ + var handlers = GetAllInheriting(typeof(BaseHandler)); + foreach (var handler in handlers){ + RegisterHandler((BaseHandler)ActivatorUtilities.CreateInstance(serviceProvider, handler)); + } + + var remotes = GetAllInheriting(typeof(BaseRemote)); + foreach (var remote in remotes){ + RegisterRemote((BaseRemote)ActivatorUtilities.CreateInstance(serviceProvider, remote)); + } + } + + public static void StartJaeger( + Server server, + String serviceName, + double probabilisticSamplerParam) + { + // TODO understand and change this loggerFactory + System.Environment.SetEnvironmentVariable("JAEGER_SERVICE_NAME", serviceName); + System.Environment.SetEnvironmentVariable("JAEGER_SAMPLER_PARAM", probabilisticSamplerParam.ToString()); + if (System.Environment.GetEnvironmentVariable("JAEGER_AGENT_HOST") == null) + { + System.Environment.SetEnvironmentVariable("JAEGER_AGENT_HOST", "localhost"); + } + if (System.Environment.GetEnvironmentVariable("JAEGER_AGENT_PORT") == null) + { + System.Environment.SetEnvironmentVariable("JAEGER_AGENT_PORT", "6831"); + } + var loggingFactory = new Microsoft.Extensions.Logging.LoggerFactory(); + var config = Configuration.FromEnv(loggingFactory); + var sampler = new ProbabilisticSampler(config.SamplerConfig.Param.Value); + var reporter = new RemoteReporter.Builder() + .WithLoggerFactory(loggingFactory) + .WithSender(new UdpSender(config.ReporterConfig.SenderConfig.AgentHost, config.ReporterConfig.SenderConfig.AgentPort.Value, 0)) + .Build(); + _tracer = new Tracer.Builder(serviceName) + .WithLoggerFactory(loggingFactory) + .WithSampler(sampler) + .WithReporter(reporter) + .WithTag("local.id", server.Id) + .WithTag("local.type", server.Type) + .WithTag("span.kind", "sidecar") + .Build(); + if (!GlobalTracer.IsRegistered()){ + GlobalTracer.Register(_tracer); + } + } + + private static void RegisterGracefulShutdown(){ + Console.CancelKeyPress += (_, ea) => + { + _processedSigint = true; + Console.WriteLine("Received SIGINT (Ctrl+C), executing on signal function"); + OnSignal(); + Terminate(); + }; + + AppDomain.CurrentDomain.ProcessExit += (_, ea) => + { + if (_processedSigint) { + Console.WriteLine("Ignoring SIGTERM, already processed SIGINT"); + } else{ + Console.WriteLine("Received SIGTERM, executing on signal function"); + OnSignal(); + Terminate(); + } + }; + } + + private static void RegisterRemote(BaseRemote remote) + { + string className = DefaultRemoteNameFunc(remote.GetName()); + RegisterRemote(remote, className, DefaultRemoteNameFunc); + } + + private static void RegisterRemote(BaseRemote remote, string name, RemoteNameFunc remoteNameFunc) + { + Dictionary m = remote.GetRemotesMap(); + foreach (KeyValuePair kvp in m) + { + var rn = remoteNameFunc(kvp.Key); + var remoteName = $"{name}.{rn}"; + if (RemotesDict.ContainsKey(remoteName)) + { + throw new PitayaException($"tried to register same remote twice! remote name: {remoteName}"); + } + + Logger.Info("registering remote {0}", remoteName); + RemotesDict[remoteName] = kvp.Value; + } + } + + private static void RegisterHandler(BaseHandler handler) + { + string className = DefaultRemoteNameFunc(handler.GetName()); + RegisterHandler(handler, className, DefaultRemoteNameFunc); + } + + public static void RegisterHandler(BaseHandler handler, string name, RemoteNameFunc remoteNameFunc) + { + Dictionary m = handler.GetRemotesMap(); + foreach (KeyValuePair kvp in m) + { + var rn = remoteNameFunc(kvp.Key); + var handlerName = $"{name}.{rn}"; + if (HandlersDict.ContainsKey(handlerName)) + { + throw new PitayaException($"tried to register same remote twice! remote name: {handlerName}"); + } + + Logger.Info("registering handler {0}", handlerName); + HandlersDict[handlerName] = kvp.Value; + } + } + + public static void SetSerializer(ISerializer s) + { + _serializer = s; + } + + public static void Terminate() + { + if (_isInitialized){ + UnsetServiceDiscoveryListener(); + _client.StopPitaya(new Google.Protobuf.WellKnownTypes.Empty()); + ShutdownSidecar(); + } + } + + public static async void TerminateAsync() + { + if (_isInitialized){ + UnsetServiceDiscoveryListener(); + await _client.StopPitayaAsync(new Google.Protobuf.WellKnownTypes.Empty()); + await ShutdownSidecarAsync(); + } + } + + private static void SetServiceDiscoveryListener(Action cb) + { + _onSDEvent += cb; + } + + private static void UnsetServiceDiscoveryListener() + { + if (_onSDEvent != null) + { + _onSDEvent = null; + } + } + } +} diff --git a/csharp/NPitaya/src/PitayaCluster.RPC.cs b/csharp/NPitaya/src/PitayaCluster.RPC.cs new file mode 100644 index 00000000..04d4ebc7 --- /dev/null +++ b/csharp/NPitaya/src/PitayaCluster.RPC.cs @@ -0,0 +1,156 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Google.Protobuf; +using NPitaya.Metrics; +using NPitaya.Models; +using NPitaya.Serializer; +using NPitaya.Protos; +using static NPitaya.Utils.Utils; + +namespace NPitaya +{ + public partial class PitayaCluster + { + private static async Task HandleIncomingRpc(Request req) + { + Response res = null; + String route = req.Msg.Route; + bool success = false; + var sw = Stopwatch.StartNew(); + try{ + res = await RPCCbFuncImpl(req, sw); + success = true; + return res; + } + catch (Exception e) + { + var innerMostException = e; + while (innerMostException.InnerException != null) + innerMostException = innerMostException.InnerException; + + Logger.Error("Exception thrown in handler, error:{0}", + innerMostException.Message); // TODO externalize method and only print stacktrace when debug +#if NPITAYA_DEBUG + // If we are compiling with a Debug define, we want to print a stacktrace whenever a route + // throws an exception. + Logger.Error("Stacktrace: {0}", innerMostException.StackTrace); +#endif + res = GetErrorResponse("PIT-500", innerMostException.Message); + return res; + } + finally + { + if (success) + { + MetricsReporters.ReportTimer(Metrics.Constants.Status.success.ToString(), route, + "handler", "", sw); + } + else + { + MetricsReporters.ReportTimer(Metrics.Constants.Status.fail.ToString(), route, + "handler", "PIT-500", sw); + } + } + } + + //private static Request BuildRequestData(IntPtr reqBufferPtr) + //{ + // var reqBuffer = (MemoryBuffer) Marshal.PtrToStructure(reqBufferPtr, typeof(MemoryBuffer)); + + // Request req = new Request(); + // req.MergeFrom(new CodedInputStream(reqBuffer.GetData())); + // return req; + //} + + private static async Task RPCCbFuncImpl(Request req, Stopwatch sw) + { + Response response; + switch (req.Type) + { + case RPCType.User: + response = await HandleRpc(req, RPCType.User, sw); + break; + case RPCType.Sys: + response = await HandleRpc(req, RPCType.Sys, sw); + break; + default: + throw new Exception($"invalid rpc type, argument:{req.Type}"); + } + + return response; + } + + internal static async Task HandleRpc(Protos.Request req, RPCType type, Stopwatch sw) + { + byte[] data = req.Msg.Data.ToByteArray(); + Route route = Route.FromString(req.Msg.Route); + + string handlerName = $"{route.service}.{route.method}"; + + PitayaSession s = null; + var response = new Response(); + + RemoteMethod handler; + if (type == RPCType.Sys) + { + s = new Models.PitayaSession(req.Session, req.FrontendID); + if (!HandlersDict.ContainsKey(handlerName)) + { + response = GetErrorResponse("PIT-404", + $"remote/handler not found! remote/handler name: {handlerName}"); + return response; + } + + handler = HandlersDict[handlerName]; + MetricsReporters.ReportMessageProccessDelay(req.Msg.Route,"local", sw); + } + else + { + if (!RemotesDict.ContainsKey(handlerName)) + { + response = GetErrorResponse("PIT-404", + $"remote/handler not found! remote/handler name: {handlerName}"); + return response; + } + + handler = RemotesDict[handlerName]; + MetricsReporters.ReportMessageProccessDelay(req.Msg.Route,"remote", sw); + } + + Task ans; + if (handler.ArgType != null) + { + var arg = _serializer.Unmarshal(data, handler.ArgType); + if (type == RPCType.Sys) + ans = handler.Method.Invoke(handler.Obj, new[] {s, arg}) as Task; + else + ans = handler.Method.Invoke(handler.Obj, new[] {arg}) as Task; + } + else + { + if (type == RPCType.Sys) + ans = handler.Method.Invoke(handler.Obj, new object[] {s}) as Task; + else + ans = handler.Method.Invoke(handler.Obj, new object[] { }) as Task; + } + + await ans; + byte[] ansBytes; + + if (handler.ReturnType != typeof(void)) + { + ansBytes = SerializerUtils.SerializeOrRaw(ans.GetType(). + GetProperty("Result") + ?.GetValue(ans), _serializer); + } + else + { + ansBytes = new byte[]{}; + } + response.Data = ByteString.CopyFrom(ansBytes); + return response; + } + } +} diff --git a/csharp/NPitaya/src/PitayaException.cs b/csharp/NPitaya/src/PitayaException.cs new file mode 100644 index 00000000..0f6c4827 --- /dev/null +++ b/csharp/NPitaya/src/PitayaException.cs @@ -0,0 +1,22 @@ +using System; + +namespace NPitaya +{ + public class PitayaException : Exception + { + public PitayaException() + : base() { } + + public PitayaException(string message) + : base(message) { } + + public PitayaException(string format, params object[] args) + : base(string.Format(format, args)) { } + + public PitayaException(string message, Exception innerException) + : base(message, innerException) { } + + public PitayaException(string format, Exception innerException, params object[] args) + : base(string.Format(format, args), innerException) { } + } +} \ No newline at end of file diff --git a/csharp/NPitaya/src/Serializer/ISerializer.cs b/csharp/NPitaya/src/Serializer/ISerializer.cs new file mode 100644 index 00000000..63b05fa4 --- /dev/null +++ b/csharp/NPitaya/src/Serializer/ISerializer.cs @@ -0,0 +1,10 @@ +using System; + +namespace NPitaya.Serializer +{ + public interface ISerializer + { + byte[] Marshal(object o); + object Unmarshal(byte[] bytes, Type t); + } +} \ No newline at end of file diff --git a/csharp/NPitaya/src/Serializer/JSONSerializer.cs b/csharp/NPitaya/src/Serializer/JSONSerializer.cs new file mode 100644 index 00000000..97159908 --- /dev/null +++ b/csharp/NPitaya/src/Serializer/JSONSerializer.cs @@ -0,0 +1,20 @@ +using System; +using System.Text; +using PitayaSimpleJson; + +namespace NPitaya.Serializer +{ + public class JSONSerializer: ISerializer + { + public byte[] Marshal(object o) + { + return Encoding.UTF8.GetBytes(PitayaSimpleJson.SimpleJson.SerializeObject(o)); + } + + public object Unmarshal(byte[] bytes, Type t) + { + if (bytes.Length == 0) bytes = Encoding.UTF8.GetBytes("{}"); + return PitayaSimpleJson.SimpleJson.DeserializeObject(Encoding.UTF8.GetString(bytes), t); + } + } +} \ No newline at end of file diff --git a/csharp/NPitaya/src/Serializer/ProtobufSerializer.cs b/csharp/NPitaya/src/Serializer/ProtobufSerializer.cs new file mode 100644 index 00000000..f1a45d56 --- /dev/null +++ b/csharp/NPitaya/src/Serializer/ProtobufSerializer.cs @@ -0,0 +1,33 @@ +using System; +using Google.Protobuf; + +namespace NPitaya.Serializer +{ + public class ProtobufSerializer: ISerializer + { + public byte[] Marshal(object o) + { + if (o == null) return new byte[]{}; + if (!(o is IMessage)) + { + throw new PitayaException("Cannot serialize a type that doesn't implement IMessage"); + } + + if (o == null) return new byte[] { }; + + return ((IMessage) o).ToByteArray(); + } + + public object Unmarshal(byte[] bytes, Type t) + { + if (!typeof(IMessage).IsAssignableFrom(t)) + { + throw new PitayaException("Cannot deserialize to a type that doesn't implement IMessage"); + + } + var res = Activator.CreateInstance(t); + ((IMessage)res).MergeFrom(bytes); + return res; + } + } +} diff --git a/csharp/NPitaya/src/Serializer/SerializerUtils.cs b/csharp/NPitaya/src/Serializer/SerializerUtils.cs new file mode 100644 index 00000000..41a1c0a4 --- /dev/null +++ b/csharp/NPitaya/src/Serializer/SerializerUtils.cs @@ -0,0 +1,15 @@ +namespace NPitaya.Serializer +{ + public class SerializerUtils + { + public static byte[] SerializeOrRaw(object obj, ISerializer serializer) + { + if (obj is byte[]) + { + return (byte[])obj; + } + + return serializer.Marshal(obj); + } + } +} \ No newline at end of file diff --git a/csharp/NPitaya/src/Utils/LimitedConcurrencyLevelTaskScheduler.cs b/csharp/NPitaya/src/Utils/LimitedConcurrencyLevelTaskScheduler.cs new file mode 100644 index 00000000..1de69fd9 --- /dev/null +++ b/csharp/NPitaya/src/Utils/LimitedConcurrencyLevelTaskScheduler.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace NPitaya.Utils +{ + // Provides a task scheduler that ensures a maximum concurrency level while + // running on top of the thread pool. + public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler + { + // Indicates whether the current thread is processing work items. + [ThreadStatic] + private static bool _currentThreadIsProcessingItems; + + // The list of tasks to be executed + private readonly LinkedList _tasks = new LinkedList(); // protected by lock(_tasks) + + // The maximum concurrency level allowed by this scheduler. + private readonly int _maxDegreeOfParallelism; + + // Indicates whether the scheduler is currently processing work items. + private int _delegatesQueuedOrRunning = 0; + + // Creates a new instance with the specified degree of parallelism. + public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism) + { + if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException("maxDegreeOfParallelism"); + _maxDegreeOfParallelism = maxDegreeOfParallelism; + } + + // Queues a task to the scheduler. + protected sealed override void QueueTask(Task task) + { + // Add the task to the list of tasks to be processed. If there aren't enough + // delegates currently queued or running to process tasks, schedule another. + lock (_tasks) + { + _tasks.AddLast(task); + if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism) + { + ++_delegatesQueuedOrRunning; + NotifyThreadPoolOfPendingWork(); + } + } + } + + // Inform the ThreadPool that there's work to be executed for this scheduler. + private void NotifyThreadPoolOfPendingWork() + { + ThreadPool.UnsafeQueueUserWorkItem(_ => + { + // Note that the current thread is now processing work items. + // This is necessary to enable inlining of tasks into this thread. + _currentThreadIsProcessingItems = true; + try + { + // Process all available items in the queue. + while (true) + { + Task item; + lock (_tasks) + { + // When there are no more items to be processed, + // note that we're done processing, and get out. + if (_tasks.Count == 0) + { + --_delegatesQueuedOrRunning; + break; + } + + // Get the next item from the queue + item = _tasks.First.Value; + _tasks.RemoveFirst(); + } + + // Execute the task we pulled out of the queue + base.TryExecuteTask(item); + } + } + // We're done processing items on the current thread + finally { _currentThreadIsProcessingItems = false; } + }, null); + } + + // Attempts to execute the specified task on the current thread. + protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) + { + // If this thread isn't already processing a task, we don't support inlining + if (!_currentThreadIsProcessingItems) return false; + + // If the task was previously queued, remove it from the queue + if (taskWasPreviouslyQueued) + // Try to run the task. + if (TryDequeue(task)) + return base.TryExecuteTask(task); + else + return false; + else + return base.TryExecuteTask(task); + } + + // Attempt to remove a previously scheduled task from the scheduler. + protected sealed override bool TryDequeue(Task task) + { + lock (_tasks) return _tasks.Remove(task); + } + + // Gets the maximum concurrency level supported by this scheduler. + public sealed override int MaximumConcurrencyLevel { get { return _maxDegreeOfParallelism; } } + + // Gets an enumerable of the tasks currently scheduled on this scheduler. + protected sealed override IEnumerable GetScheduledTasks() + { + bool lockTaken = false; + try + { + Monitor.TryEnter(_tasks, ref lockTaken); + if (lockTaken) return _tasks; + else throw new NotSupportedException(); + } + finally + { + if (lockTaken) Monitor.Exit(_tasks); + } + } + } +} diff --git a/csharp/NPitaya/src/Utils/PitayaSimpleJson.cs b/csharp/NPitaya/src/Utils/PitayaSimpleJson.cs new file mode 100644 index 00000000..2df3a450 --- /dev/null +++ b/csharp/NPitaya/src/Utils/PitayaSimpleJson.cs @@ -0,0 +1,1936 @@ +//----------------------------------------------------------------------- +// +// Copyright (c) 2011, The Outercurve Foundation. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.opensource.org/licenses/mit-license.php +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me) +// https://github.com/facebook-csharp-sdk/simple-json +//----------------------------------------------------------------------- + +// NOTE: uncomment the following line to make SimpleJson class internal. +//#define SIMPLE_JSON_INTERNAL + +// NOTE: uncomment the following line to make JsonArray and JsonObject class internal. +//#define SIMPLE_JSON_OBJARRAYINTERNAL + +// NOTE: uncomment the following line to enable dynamic support. +//#define SIMPLE_JSON_DYNAMIC + +// NOTE: uncomment the following line to enable DataContract support. +#define SIMPLE_JSON_DATACONTRACT + +// NOTE: uncomment the following line to use Reflection.Emit (better performance) instead of method.invoke(). +// don't enable ReflectionEmit for WinRT, Silverlight and WP7. +//#define SIMPLE_JSON_REFLECTIONEMIT + +// NOTE: uncomment the following line if you are compiling under Window Metro style application/library. +// usually already defined in properties +//#define NETFX_CORE; + +// original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +#if SIMPLE_JSON_DYNAMIC +using System.Dynamic; +#endif +using System.Globalization; +using System.Reflection; +#if SIMPLE_JSON_REFLECTIONEMIT +using System.Reflection.Emit; +#endif +#if SIMPLE_JSON_DATACONTRACT +using System.Runtime.Serialization; +#endif +using System.Text; +using PitayaSimpleJson.Reflection; + +namespace PitayaSimpleJson +{ + #region JsonArray + + /// + /// Represents the json array. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] + #if SIMPLE_JSON_OBJARRAYINTERNAL + internal + #else + public + #endif + class JsonArray : List + { + /// + /// Initializes a new instance of the class. + /// + public JsonArray() { } + + /// + /// Initializes a new instance of the class. + /// + /// The capacity of the json array. + public JsonArray(int capacity) : base(capacity) { } + + /// + /// The json representation of the array. + /// + /// The json representation of the array. + public override string ToString() + { + return SimpleJson.SerializeObject(this) ?? string.Empty; + } + } + + #endregion + + #region JsonObject + + /// + /// Represents the json object. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] + #if SIMPLE_JSON_OBJARRAYINTERNAL + internal + #else + public + #endif + class JsonObject : + #if SIMPLE_JSON_DYNAMIC + DynamicObject, + #endif + IDictionary + { + /// + /// The internal member dictionary. + /// + private readonly Dictionary _members = new Dictionary(); + + /// + /// Gets the at the specified index. + /// + /// + public object this[int index] + { + get { return GetAtIndex(_members, index); } + } + + internal static object GetAtIndex(IDictionary obj, int index) + { + if (obj == null) + throw new ArgumentNullException("obj"); + + if (index >= obj.Count) + throw new ArgumentOutOfRangeException("index"); + + int i = 0; + foreach (KeyValuePair o in obj) + if (i++ == index) return o.Value; + + return null; + } + + /// + /// Adds the specified key. + /// + /// The key. + /// The value. + public void Add(string key, object value) + { + _members.Add(key, value); + } + + /// + /// Determines whether the specified key contains key. + /// + /// The key. + /// + /// true if the specified key contains key; otherwise, false. + /// + public bool ContainsKey(string key) + { + return _members.ContainsKey(key); + } + + /// + /// Gets the keys. + /// + /// The keys. + public ICollection Keys + { + get { return _members.Keys; } + } + + /// + /// Removes the specified key. + /// + /// The key. + /// + public bool Remove(string key) + { + return _members.Remove(key); + } + + /// + /// Tries the get value. + /// + /// The key. + /// The value. + /// + public bool TryGetValue(string key, out object value) + { + return _members.TryGetValue(key, out value); + } + + /// + /// Gets the values. + /// + /// The values. + public ICollection Values + { + get { return _members.Values; } + } + + /// + /// Gets or sets the with the specified key. + /// + /// + public object this[string key] + { + get { return _members[key]; } + set { _members[key] = value; } + } + + /// + /// Adds the specified item. + /// + /// The item. + public void Add(KeyValuePair item) + { + _members.Add(item.Key, item.Value); + } + + /// + /// Clears this instance. + /// + public void Clear() + { + _members.Clear(); + } + + /// + /// Determines whether [contains] [the specified item]. + /// + /// The item. + /// + /// true if [contains] [the specified item]; otherwise, false. + /// + public bool Contains(KeyValuePair item) + { + return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value; + } + + /// + /// Copies to. + /// + /// The array. + /// Index of the array. + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + int num = Count; + foreach (KeyValuePair kvp in this) + { + array[arrayIndex++] = kvp; + + if (--num <= 0) + return; + } + } + + /// + /// Gets the count. + /// + /// The count. + public int Count + { + get { return _members.Count; } + } + + /// + /// Gets a value indicating whether this instance is read only. + /// + /// + /// true if this instance is read only; otherwise, false. + /// + public bool IsReadOnly + { + get { return false; } + } + + /// + /// Removes the specified item. + /// + /// The item. + /// + public bool Remove(KeyValuePair item) + { + return _members.Remove(item.Key); + } + + /// + /// Gets the enumerator. + /// + /// + public IEnumerator> GetEnumerator() + { + return _members.GetEnumerator(); + } + + /// + /// Returns an enumerator that iterates through a collection. + /// + /// + /// An object that can be used to iterate through the collection. + /// + IEnumerator IEnumerable.GetEnumerator() + { + return _members.GetEnumerator(); + } + + /// + /// Returns a json that represents the current . + /// + /// + /// A json that represents the current . + /// + public override string ToString() + { + return SimpleJson.SerializeObject(this); + } + + #if SIMPLE_JSON_DYNAMIC + /// + /// Provides implementation for type conversion operations. Classes derived from the class can override this method to specify dynamic behavior for operations that convert an object from one type to another. + /// + /// Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the class, binder.Type returns the type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion. + /// The result of the type conversion operation. + /// + /// Alwasy returns true. + /// + public override bool TryConvert(ConvertBinder binder, out object result) + { + // + if (binder == (ConvertBinder)null) + throw new ArgumentNullException("binder"); + // + Type targetType = binder.Type; + + if ((targetType == typeof(IEnumerable)) || + (targetType == typeof(IEnumerable>)) || + (targetType == typeof(IDictionary)) || + #if NETFX_CORE + (targetType == typeof(IDictionary<,>)) + #else + (targetType == typeof(IDictionary)) + #endif + ) + { + result = this; + return true; + } + + return base.TryConvert(binder, out result); + } + + /// + /// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic. + /// + /// Provides information about the deletion. + /// + /// Alwasy returns true. + /// + public override bool TryDeleteMember(DeleteMemberBinder binder) + { + // + if (binder == (DeleteMemberBinder)null) + throw new ArgumentNullException("binder"); + // + return _members.Remove(binder.Name); + } + + /// + /// Provides the implementation for operations that get a value by index. Classes derived from the class can override this method to specify dynamic behavior for indexing operations. + /// + /// Provides information about the operation. + /// The indexes that are used in the operation. For example, for the sampleObject[3] operation in C# (sampleObject(3) in Visual Basic), where sampleObject is derived from the DynamicObject class, is equal to 3. + /// The result of the index operation. + /// + /// Alwasy returns true. + /// + public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) + { + if (indexes.Length == 1) + { + result = ((IDictionary)this)[(string)indexes[0]]; + return true; + } + result = (object)null; + return true; + } + + /// + /// Provides the implementation for operations that get member values. Classes derived from the class can override this method to specify dynamic behavior for operations such as getting a value for a property. + /// + /// Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive. + /// The result of the get operation. For example, if the method is called for a property, you can assign the property value to . + /// + /// Alwasy returns true. + /// + public override bool TryGetMember(GetMemberBinder binder, out object result) + { + object value; + if (_members.TryGetValue(binder.Name, out value)) + { + result = value; + return true; + } + result = (object)null; + return true; + } + + /// + /// Provides the implementation for operations that set a value by index. Classes derived from the class can override this method to specify dynamic behavior for operations that access objects by a specified index. + /// + /// Provides information about the operation. + /// The indexes that are used in the operation. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the class, is equal to 3. + /// The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the class, is equal to 10. + /// + /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown. + /// + public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) + { + if (indexes.Length == 1) + { + ((IDictionary)this)[(string)indexes[0]] = value; + return true; + } + + return base.TrySetIndex(binder, indexes, value); + } + + /// + /// Provides the implementation for operations that set member values. Classes derived from the class can override this method to specify dynamic behavior for operations such as setting a value for a property. + /// + /// Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive. + /// The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the class, the is "Test". + /// + /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.) + /// + public override bool TrySetMember(SetMemberBinder binder, object value) + { + // + if (binder == (SetMemberBinder)null) + throw new ArgumentNullException("binder"); + // + _members[binder.Name] = value; + return true; + } + + /// + /// Returns the enumeration of all dynamic member names. + /// + /// + /// A sequence that contains dynamic member names. + /// + public override IEnumerable GetDynamicMemberNames() + { + foreach (var key in Keys) + yield return key; + } + #endif + } + + #endregion +} + +namespace PitayaSimpleJson +{ + #region JsonParser + + /// + /// This class encodes and decodes JSON strings. + /// Spec. details, see http://www.json.org/ + /// + /// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList<object>) and JsonObject(IDictionary<string,object>). + /// All numbers are parsed to doubles. + /// + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class SimpleJson + { + private const int TOKEN_NONE = 0; + private const int TOKEN_CURLY_OPEN = 1; + private const int TOKEN_CURLY_CLOSE = 2; + private const int TOKEN_SQUARED_OPEN = 3; + private const int TOKEN_SQUARED_CLOSE = 4; + private const int TOKEN_COLON = 5; + private const int TOKEN_COMMA = 6; + private const int TOKEN_STRING = 7; + private const int TOKEN_NUMBER = 8; + private const int TOKEN_TRUE = 9; + private const int TOKEN_FALSE = 10; + private const int TOKEN_NULL = 11; + + private const int BUILDER_CAPACITY = 2000; + + /// + /// Parses the string json into a value + /// + /// A JSON string. + /// An IList<object>, a IDictionary<string,object>, a double, a string, null, true, or false + public static object DeserializeObject(string json) + { + object @object; + if (TryDeserializeObject(json, out @object)) + return @object; + throw new System.Runtime.Serialization.SerializationException("Invalid JSON string"); + } + + /// + /// Try parsing the json string into a value. + /// + /// + /// A JSON string. + /// + /// + /// The object. + /// + /// + /// Returns true if successfull otherwise false. + /// + public static bool TryDeserializeObject(string json, out object @object) + { + bool success = true; + if (json != null) + { + char[] charArray = json.ToCharArray(); + int index = 0; + @object = ParseValue(charArray, ref index, ref success); + } + else + @object = null; + + return success; + } + + public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy) + { + return DeserializeObject(json, type, jsonSerializerStrategy, null); + } + + public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy, object defaultValue = null) + { + object jsonObject = DeserializeObject(json); + + return type == null || jsonObject != null && + #if NETFX_CORE + jsonObject.GetType().GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()) + #else + jsonObject.GetType().IsAssignableFrom(type) + #endif + ? jsonObject + : (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type, defaultValue); + } + + public static object DeserializeObject(string json, Type type) + { + return DeserializeObject(json, type, null, null); + } + + public static T DeserializeObject(string json, T defaultValue) + { + return (T)DeserializeObject(json, typeof(T), null, defaultValue); + } + + public static T DeserializeObject(string json, IJsonSerializerStrategy jsonSerializerStrategy) + { + return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy, null); + } + + public static T DeserializeObject(string json) + { + return (T)DeserializeObject(json, typeof(T), null, null); + } + + /// + /// Converts a IDictionary<string,object> / IList<object> object into a JSON string + /// + /// A IDictionary<string,object> / IList<object> + /// Serializer strategy to use + /// A JSON encoded string, or null if object 'json' is not serializable + public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy) + { + StringBuilder builder = new StringBuilder(BUILDER_CAPACITY); + bool success = SerializeValue(jsonSerializerStrategy, json, builder); + return (success ? builder.ToString() : null); + } + + public static string SerializeObject(object json) + { + return SerializeObject(json, CurrentJsonSerializerStrategy); + } + + public static string EscapeToJavascriptString(string jsonString) + { + if (string.IsNullOrEmpty(jsonString)) + { + return jsonString; + } + + StringBuilder sb = new StringBuilder(); + char c; + + for (int i = 0; i < jsonString.Length; ) + { + c = jsonString[i++]; + + if (c == '\\') + { + int remainingLength = jsonString.Length - i; + if (remainingLength >= 2) + { + char lookahead = jsonString[i]; + if (lookahead == '\\') + { + sb.Append('\\'); + ++i; + } + else if (lookahead == '"') + { + sb.Append("\""); + ++i; + } + else if (lookahead == 't') + { + sb.Append('\t'); + ++i; + } + else if (lookahead == 'b') + { + sb.Append('\b'); + ++i; + } + else if (lookahead == 'n') + { + sb.Append('\n'); + ++i; + } + else if (lookahead == 'r') + { + sb.Append('\r'); + ++i; + } + } + } + else + { + sb.Append(c); + } + } + + return sb.ToString(); + } + + protected static IDictionary ParseObject(char[] json, ref int index, ref bool success) + { + IDictionary table = new JsonObject(); + int token; + + // { + NextToken(json, ref index); + + bool done = false; + while (!done) + { + token = LookAhead(json, index); + if (token == TOKEN_NONE) + { + success = false; + return null; + } + else if (token == TOKEN_COMMA) + NextToken(json, ref index); + else if (token == TOKEN_CURLY_CLOSE) + { + NextToken(json, ref index); + return table; + } + else + { + // name + string name = ParseString(json, ref index, ref success); + if (!success) + { + success = false; + return null; + } + + // : + token = NextToken(json, ref index); + if (token != TOKEN_COLON) + { + success = false; + return null; + } + + // value + object value = ParseValue(json, ref index, ref success); + if (!success) + { + success = false; + return null; + } + + table[name] = value; + } + } + + return table; + } + + protected static JsonArray ParseArray(char[] json, ref int index, ref bool success) + { + JsonArray array = new JsonArray(); + + // [ + NextToken(json, ref index); + + bool done = false; + while (!done) + { + int token = LookAhead(json, index); + if (token == TOKEN_NONE) + { + success = false; + return null; + } + else if (token == TOKEN_COMMA) + NextToken(json, ref index); + else if (token == TOKEN_SQUARED_CLOSE) + { + NextToken(json, ref index); + break; + } + else + { + object value = ParseValue(json, ref index, ref success); + if (!success) + return null; + array.Add(value); + } + } + + return array; + } + + protected static object ParseValue(char[] json, ref int index, ref bool success) + { + switch (LookAhead(json, index)) + { + case TOKEN_STRING: + return ParseString(json, ref index, ref success); + case TOKEN_NUMBER: + return ParseNumber(json, ref index, ref success); + case TOKEN_CURLY_OPEN: + return ParseObject(json, ref index, ref success); + case TOKEN_SQUARED_OPEN: + return ParseArray(json, ref index, ref success); + case TOKEN_TRUE: + NextToken(json, ref index); + return true; + case TOKEN_FALSE: + NextToken(json, ref index); + return false; + case TOKEN_NULL: + NextToken(json, ref index); + return null; + case TOKEN_NONE: + break; + } + + success = false; + return null; + } + + protected static string ParseString(char[] json, ref int index, ref bool success) + { + StringBuilder s = new StringBuilder(BUILDER_CAPACITY); + char c; + + EatWhitespace(json, ref index); + + // " + c = json[index++]; + + bool complete = false; + while (!complete) + { + if (index == json.Length) + { + break; + } + + c = json[index++]; + if (c == '"') + { + complete = true; + break; + } + else if (c == '\\') + { + if (index == json.Length) + break; + c = json[index++]; + if (c == '"') + s.Append('"'); + else if (c == '\\') + s.Append('\\'); + else if (c == '/') + s.Append('/'); + else if (c == 'b') + s.Append('\b'); + else if (c == 'f') + s.Append('\f'); + else if (c == 'n') + s.Append('\n'); + else if (c == 'r') + s.Append('\r'); + else if (c == 't') + s.Append('\t'); + else if (c == 'u') + { + int remainingLength = json.Length - index; + if (remainingLength >= 4) + { + // parse the 32 bit hex into an integer codepoint + uint codePoint; + if ( + !(success = + UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, + CultureInfo.InvariantCulture, out codePoint))) + return ""; + + // convert the integer codepoint to a unicode char and add to string + + if (0xD800 <= codePoint && codePoint <= 0xDBFF) // if high surrogate + { + index += 4; // skip 4 chars + remainingLength = json.Length - index; + if (remainingLength >= 6) + { + uint lowCodePoint; + if (new string(json, index, 2) == "\\u" && + UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, + CultureInfo.InvariantCulture, out lowCodePoint)) + { + if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate + { + s.Append((char)codePoint); + s.Append((char)lowCodePoint); + index += 6; // skip 6 chars + continue; + } + } + } + success = false; // invalid surrogate pair + return ""; + } + #if SILVERLIGHT + s.Append(ConvertFromUtf32((int)codePoint)); + #else + s.Append(Char.ConvertFromUtf32((int)codePoint)); + #endif + // skip 4 chars + index += 4; + } + else + break; + } + } + else + s.Append(c); + } + + if (!complete) + { + success = false; + return null; + } + + return s.ToString(); + } + + #if SILVERLIGHT + private static string ConvertFromUtf32(int utf32) + { + // http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm + if (utf32 < 0 || utf32 > 0x10FFFF) + throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF."); + if (0xD800 <= utf32 && utf32 <= 0xDFFF) + throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range."); + if (utf32 < 0x10000) + return new string((char)utf32, 1); + utf32 -= 0x10000; + return new string(new char[] {(char) ((utf32 >> 10) + 0xD800),(char) (utf32 % 0x0400 + 0xDC00)}); + } + #endif + + protected static object ParseNumber(char[] json, ref int index, ref bool success) + { + EatWhitespace(json, ref index); + + int lastIndex = GetLastIndexOfNumber(json, index); + int charLength = (lastIndex - index) + 1; + + object returnNumber; + string str = new string(json, index, charLength); + if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1) + { + double number; + success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); + returnNumber = number; + } + else + { + long number; + success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); + returnNumber = number; + } + + index = lastIndex + 1; + return returnNumber; + } + + protected static int GetLastIndexOfNumber(char[] json, int index) + { + int lastIndex; + + for (lastIndex = index; lastIndex < json.Length; lastIndex++) + if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break; + return lastIndex - 1; + } + + protected static void EatWhitespace(char[] json, ref int index) + { + for (; index < json.Length; index++) + if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break; + } + + protected static int LookAhead(char[] json, int index) + { + int saveIndex = index; + return NextToken(json, ref saveIndex); + } + + [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] + protected static int NextToken(char[] json, ref int index) + { + EatWhitespace(json, ref index); + + if (index == json.Length) + return TOKEN_NONE; + + char c = json[index]; + index++; + switch (c) + { + case '{': + return TOKEN_CURLY_OPEN; + case '}': + return TOKEN_CURLY_CLOSE; + case '[': + return TOKEN_SQUARED_OPEN; + case ']': + return TOKEN_SQUARED_CLOSE; + case ',': + return TOKEN_COMMA; + case '"': + return TOKEN_STRING; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + return TOKEN_NUMBER; + case ':': + return TOKEN_COLON; + } + index--; + + int remainingLength = json.Length - index; + + // false + if (remainingLength >= 5) + { + if (json[index] == 'f' && + json[index + 1] == 'a' && + json[index + 2] == 'l' && + json[index + 3] == 's' && + json[index + 4] == 'e') + { + index += 5; + return TOKEN_FALSE; + } + } + + // true + if (remainingLength >= 4) + { + if (json[index] == 't' && + json[index + 1] == 'r' && + json[index + 2] == 'u' && + json[index + 3] == 'e') + { + index += 4; + return TOKEN_TRUE; + } + } + + // null + if (remainingLength >= 4) + { + if (json[index] == 'n' && + json[index + 1] == 'u' && + json[index + 2] == 'l' && + json[index + 3] == 'l') + { + index += 4; + return TOKEN_NULL; + } + } + + return TOKEN_NONE; + } + + protected static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder) + { + bool success = true; + + if (value is string) + success = SerializeString((string)value, builder); + else if (value is IDictionary) + { + IDictionary dict = (IDictionary)value; + success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder); + } + else if (value is IDictionary) + { + IDictionary dict = (IDictionary)value; + success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder); + } + else if (value is IEnumerable) + success = SerializeArray(jsonSerializerStrategy, (IEnumerable)value, builder); + else if (IsNumeric(value)) + success = SerializeNumber(value, builder); + else if (value is Boolean) + builder.Append((bool)value ? "true" : "false"); + else if (value == null) + builder.Append("null"); + else + { + object serializedObject; + success = jsonSerializerStrategy.SerializeNonPrimitiveObject(value, out serializedObject); + if (success) + SerializeValue(jsonSerializerStrategy, serializedObject, builder); + } + + return success; + } + + protected static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder) + { + builder.Append("{"); + + IEnumerator ke = keys.GetEnumerator(); + IEnumerator ve = values.GetEnumerator(); + + bool first = true; + while (ke.MoveNext() && ve.MoveNext()) + { + object key = ke.Current; + object value = ve.Current; + + if (!first) + builder.Append(","); + + if (key is string) + SerializeString((string)key, builder); + else + if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false; + + builder.Append(":"); + if (!SerializeValue(jsonSerializerStrategy, value, builder)) + return false; + + first = false; + } + + builder.Append("}"); + return true; + } + + protected static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder) + { + builder.Append("["); + + bool first = true; + foreach (object value in anArray) + { + if (!first) + builder.Append(","); + + if (!SerializeValue(jsonSerializerStrategy, value, builder)) + return false; + + first = false; + } + + builder.Append("]"); + return true; + } + + protected static bool SerializeString(string aString, StringBuilder builder) + { + builder.Append("\""); + + char[] charArray = aString.ToCharArray(); + for (int i = 0; i < charArray.Length; i++) + { + char c = charArray[i]; + if (c == '"') + builder.Append("\\\""); + else if (c == '\\') + builder.Append("\\\\"); + else if (c == '\b') + builder.Append("\\b"); + else if (c == '\f') + builder.Append("\\f"); + else if (c == '\n') + builder.Append("\\n"); + else if (c == '\r') + builder.Append("\\r"); + else if (c == '\t') + builder.Append("\\t"); + else + builder.Append(c); + } + + builder.Append("\""); + return true; + } + + protected static bool SerializeNumber(object number, StringBuilder builder) + { + if (number is long) + { + builder.Append(((long)number).ToString(CultureInfo.InvariantCulture)); + } + else if (number is ulong) + { + builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture)); + } + else if (number is int) + { + builder.Append(((int)number).ToString(CultureInfo.InvariantCulture)); + } + else if (number is uint) + { + builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture)); + } + else if (number is decimal) + { + builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture)); + } + else if (number is float) + { + builder.Append(((float)number).ToString(CultureInfo.InvariantCulture)); + } + else + { + builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture)); + } + + return true; + } + + /// + /// Determines if a given object is numeric in any way + /// (can be integer, double, null, etc). + /// + protected static bool IsNumeric(object value) + { + if (value is sbyte) return true; + if (value is byte) return true; + if (value is short) return true; + if (value is ushort) return true; + if (value is int) return true; + if (value is uint) return true; + if (value is long) return true; + if (value is ulong) return true; + if (value is float) return true; + if (value is double) return true; + if (value is decimal) return true; + return false; + } + + private static IJsonSerializerStrategy currentJsonSerializerStrategy; + public static IJsonSerializerStrategy CurrentJsonSerializerStrategy + { + get + { + // todo: implement locking mechanism. + return currentJsonSerializerStrategy ?? + (currentJsonSerializerStrategy = + #if SIMPLE_JSON_DATACONTRACT + DataContractJsonSerializerStrategy + #else + PocoJsonSerializerStrategy + #endif + ); + } + + set + { + currentJsonSerializerStrategy = value; + } + } + + private static PocoJsonSerializerStrategy pocoJsonSerializerStrategy; + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] + public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy + { + get + { + // todo: implement locking mechanism. + return pocoJsonSerializerStrategy ?? (pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy()); + } + } + + #if SIMPLE_JSON_DATACONTRACT + + private static DataContractJsonSerializerStrategy dataContractJsonSerializerStrategy; + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] + public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy + { + get + { + // todo: implement locking mechanism. + return dataContractJsonSerializerStrategy ?? (dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy()); + } + } + + #endif + } + + #endregion + + #region Simple Json Serializer Strategies + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + interface IJsonSerializerStrategy + { + bool SerializeNonPrimitiveObject(object input, out object output); + + object DeserializeObject(object value, Type type, object defaultValue = null); + } + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class PocoJsonSerializerStrategy : IJsonSerializerStrategy + { + internal CacheResolver CacheResolver; + + private static readonly string[] Iso8601Format = new string[] + { + @"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z", + @"yyyy-MM-dd\THH:mm:ss\Z", + @"yyyy-MM-dd\THH:mm:ssK" + }; + + public PocoJsonSerializerStrategy() + { + CacheResolver = new CacheResolver(BuildMap); + } + + protected virtual void BuildMap(Type type, SafeDictionary memberMaps) + { + #if NETFX_CORE + foreach (PropertyInfo info in type.GetTypeInfo().DeclaredProperties) { + var getMethod = info.GetMethod; + if(getMethod==null || !getMethod.IsPublic || getMethod.IsStatic) continue; + #else + foreach (PropertyInfo info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) + { + #endif + memberMaps.Add(info.Name, new CacheResolver.MemberMap(info)); + } + #if NETFX_CORE + foreach (FieldInfo info in type.GetTypeInfo().DeclaredFields) { + if(!info.IsPublic || info.IsStatic) continue; + #else + foreach (FieldInfo info in type.GetFields(BindingFlags.Public | BindingFlags.Instance)) + { + #endif + memberMaps.Add(info.Name, new CacheResolver.MemberMap(info)); + } + } + + public virtual bool SerializeNonPrimitiveObject(object input, out object output) + { + return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output); + } + + [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] + public virtual object DeserializeObject(object value, Type type, object defaultInstance = null) + { + object obj = null; + if (value is string) + { + string str = value as string; + if(!string.IsNullOrEmpty(str) && (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime)) )) + obj = DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + else + obj = str; + } + else if (value is bool) + obj = value; + else if (value == null) + obj = null; + else if ((value is long && type == typeof(long)) || (value is double && type == typeof(double))) + obj = value; + else if ((value is double && type != typeof(double)) || (value is long && type != typeof(long))) + { + obj = + #if NETFX_CORE + type == typeof(int) || type == typeof(long) || type == typeof(double) ||type == typeof(float) || type == typeof(bool) || type == typeof(decimal) ||type == typeof(byte) || type == typeof(short) + #else + typeof(IConvertible).IsAssignableFrom(type) + #endif + ? Convert.ChangeType(value, type, CultureInfo.InvariantCulture) : value; + } + else + { + if (value is IDictionary) + { + IDictionary jsonObject = (IDictionary) value; + + if (ReflectionUtils.IsTypeDictionary(type)) + { + // if dictionary then + #if NETFX_CORE + Type keyType = type.GetTypeInfo().GenericTypeArguments[0]; + Type valueType = type.GetTypeInfo().GenericTypeArguments[1]; + #else + Type keyType = type.GetGenericArguments()[0]; + Type valueType = type.GetGenericArguments()[1]; + #endif + + Type genericType = typeof (Dictionary<,>).MakeGenericType(keyType, valueType); + + #if NETFX_CORE + dynamic dict = CacheResolver.GetNewInstance(genericType); + #else + IDictionary dict = (IDictionary) CacheResolver.GetNewInstance(genericType); + #endif + foreach (KeyValuePair kvp in jsonObject) + { + dict.Add(DeserializeObject(kvp.Key, keyType), DeserializeObject(kvp.Value, valueType)); + } + + obj = dict; + } + else + { + if(defaultInstance != null){ + obj = defaultInstance; + }else{ + obj = CacheResolver.GetNewInstance(type); + } + + SafeDictionary maps = CacheResolver.LoadMaps(type); + + if (maps == null) + { + obj = value; + } + else + { + foreach (KeyValuePair keyValuePair in maps) + { + CacheResolver.MemberMap v = keyValuePair.Value; + if (v.Setter == null) + continue; + + string jsonKey = keyValuePair.Key; + if (jsonObject.ContainsKey(jsonKey)) + { + object jsonValue = DeserializeObject(jsonObject[jsonKey], v.Type); + v.Setter(obj, jsonValue); + } + } + } + } + } + else if (value is IList) + { + IList jsonObject = (IList) value; + IList list = null; + + if (type.IsArray) + { + list = (IList) Activator.CreateInstance(type, jsonObject.Count); + int i = 0; + foreach (object o in jsonObject) + list[i++] = DeserializeObject(o, type.GetElementType()); + } + else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || + #if NETFX_CORE + typeof(IList).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()) + #else + typeof (IList).IsAssignableFrom(type) + #endif + ) + { + #if NETFX_CORE + Type innerType = type.GetTypeInfo().GenericTypeArguments[0]; + #else + Type innerType = type.GetGenericArguments()[0]; + #endif + Type genericType = typeof (List<>).MakeGenericType(innerType); + list = (IList) CacheResolver.GetNewInstance(genericType); + foreach (object o in jsonObject) + list.Add(DeserializeObject(o, innerType)); + } + + obj = list; + } + + return obj; + } + + if (ReflectionUtils.IsNullableType(type)) + return ReflectionUtils.ToNullableType(obj, type); + + return obj; + } + + protected virtual object SerializeEnum(Enum p) + { + return Convert.ToDouble(p, CultureInfo.InvariantCulture); + } + + protected virtual bool TrySerializeKnownTypes(object input, out object output) + { + bool returnValue = true; + if (input is DateTime) + output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture); + else if (input is Guid) + output = ((Guid)input).ToString("D"); + else if (input is Uri) + output = input.ToString(); + else if (input is Enum) + output = SerializeEnum((Enum)input); + else + { + returnValue = false; + output = null; + } + + return returnValue; + } + + protected virtual bool TrySerializeUnknownTypes(object input, out object output) + { + output = null; + + // todo: implement caching for types + Type type = input.GetType(); + + if (type.FullName == null) + return false; + + IDictionary obj = new JsonObject(); + + SafeDictionary maps = CacheResolver.LoadMaps(type); + + foreach (KeyValuePair keyValuePair in maps) + { + if (keyValuePair.Value.Getter != null) + obj.Add(keyValuePair.Key, keyValuePair.Value.Getter(input)); + } + + output = obj; + return true; + } + } + + #if SIMPLE_JSON_DATACONTRACT + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy + { + public DataContractJsonSerializerStrategy() + { + CacheResolver = new CacheResolver(BuildMap); + } + + protected override void BuildMap(Type type, SafeDictionary map) + { + bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null; + if (!hasDataContract) + { + base.BuildMap(type, map); + return; + } + + string jsonKey; + #if NETFX_CORE + foreach (PropertyInfo info in type.GetTypeInfo().DeclaredProperties) + #else + foreach (PropertyInfo info in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) + #endif + { + if (CanAdd(info, out jsonKey)) + map.Add(jsonKey, new CacheResolver.MemberMap(info)); + } + + #if NETFX_CORE + foreach (FieldInfo info in type.GetTypeInfo().DeclaredFields) + #else + foreach (FieldInfo info in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) + #endif + { + if (CanAdd(info, out jsonKey)) + map.Add(jsonKey, new CacheResolver.MemberMap(info)); + } + + // todo implement sorting for DATACONTRACT. + } + + private static bool CanAdd(MemberInfo info, out string jsonKey) + { + jsonKey = null; + + if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null) + return false; + + DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute)); + + if (dataMemberAttribute == null) + return false; + + jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name; + return true; + } + } + #endif + + #endregion + + #region Reflection helpers + + namespace Reflection + { + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class ReflectionUtils + { + public static Attribute GetAttribute(MemberInfo info, Type type) + { + #if NETFX_CORE + if (info == null || type == null || !info.IsDefined(type)) + return null; + return info.GetCustomAttribute(type); + #else + if (info == null || type == null || !Attribute.IsDefined(info, type)) + return null; + return Attribute.GetCustomAttribute(info, type); + #endif + } + + public static Attribute GetAttribute(Type objectType, Type attributeType) + { + + #if NETFX_CORE + if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType)) + return null; + return objectType.GetTypeInfo().GetCustomAttribute(attributeType); + #else + if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType)) + return null; + return Attribute.GetCustomAttribute(objectType, attributeType); + #endif + } + + public static bool IsTypeGenericeCollectionInterface(Type type) + { + #if NETFX_CORE + if (!type.GetTypeInfo().IsGenericType) + #else + if (!type.IsGenericType) + #endif + return false; + + Type genericDefinition = type.GetGenericTypeDefinition(); + + return (genericDefinition == typeof(IList<>) || genericDefinition == typeof(ICollection<>) || genericDefinition == typeof(IEnumerable<>)); + } + + public static bool IsTypeDictionary(Type type) + { + #if NETFX_CORE + if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) + return true; + + if (!type.GetTypeInfo().IsGenericType) + return false; + #else + if (typeof(IDictionary).IsAssignableFrom(type)) + return true; + + if (!type.IsGenericType) + return false; + #endif + Type genericDefinition = type.GetGenericTypeDefinition(); + return genericDefinition == typeof(IDictionary<,>); + } + + public static bool IsNullableType(Type type) + { + return + #if NETFX_CORE + type.GetTypeInfo().IsGenericType + #else + type.IsGenericType + #endif + && type.GetGenericTypeDefinition() == typeof(Nullable<>); + } + + public static object ToNullableType(object obj, Type nullableType) + { + return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture); + } + } + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + delegate object GetHandler(object source); + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + delegate void SetHandler(object source, object value); + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + delegate void MemberMapLoader(Type type, SafeDictionary memberMaps); + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class CacheResolver + { + private readonly MemberMapLoader _memberMapLoader; + private readonly SafeDictionary> _memberMapsCache = new SafeDictionary>(); + + delegate object CtorDelegate(); + readonly static SafeDictionary ConstructorCache = new SafeDictionary(); + + public CacheResolver(MemberMapLoader memberMapLoader) + { + _memberMapLoader = memberMapLoader; + } + + [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] + public static object GetNewInstance(Type type) + { + CtorDelegate c; + if (ConstructorCache.TryGetValue(type, out c)) + return c(); + #if SIMPLE_JSON_REFLECTIONEMIT + DynamicMethod dynamicMethod = new DynamicMethod("Create" + type.FullName, typeof(object), Type.EmptyTypes, type, true); + dynamicMethod.InitLocals = true; + ILGenerator generator = dynamicMethod.GetILGenerator(); + if (type.IsValueType) + { + generator.DeclareLocal(type); + generator.Emit(OpCodes.Ldloc_0); + generator.Emit(OpCodes.Box, type); + } + else + { + ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); + if (constructorInfo == null) + throw new Exception(string.Format(CultureInfo.InvariantCulture, "Could not get constructor for {0}.", type)); + generator.Emit(OpCodes.Newobj, constructorInfo); + } + generator.Emit(OpCodes.Ret); + c = (CtorDelegate)dynamicMethod.CreateDelegate(typeof(CtorDelegate)); + ConstructorCache.Add(type, c); + return c(); + #else + #if NETFX_CORE + IEnumerable constructorInfos = type.GetTypeInfo().DeclaredConstructors; + ConstructorInfo constructorInfo = null; + foreach (ConstructorInfo item in constructorInfos) // FirstOrDefault() + { + if (item.GetParameters().Length == 0) // Default ctor - make sure it doesn't contain any parameters + { + constructorInfo = item; + break; + } + } + #else + ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); + #endif + c = delegate { return constructorInfo.Invoke(null); }; + ConstructorCache.Add(type, c); + return c(); + #endif + } + + public SafeDictionary LoadMaps(Type type) + { + if (type == null || type == typeof(object)) + return null; + SafeDictionary maps; + if (_memberMapsCache.TryGetValue(type, out maps)) + return maps; + maps = new SafeDictionary(); + _memberMapLoader(type, maps); + _memberMapsCache.Add(type, maps); + return maps; + } + + #if SIMPLE_JSON_REFLECTIONEMIT + static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) + { + DynamicMethod dynamicMethod = !owner.IsInterface + ? new DynamicMethod(name, returnType, parameterTypes, owner, true) + : new DynamicMethod(name, returnType, parameterTypes, (Module)null, true); + + return dynamicMethod; + } + #endif + + static GetHandler CreateGetHandler(FieldInfo fieldInfo) + { + #if SIMPLE_JSON_REFLECTIONEMIT + Type type = fieldInfo.FieldType; + DynamicMethod dynamicGet = CreateDynamicMethod("Get" + fieldInfo.Name, fieldInfo.DeclaringType, new Type[] { typeof(object) }, fieldInfo.DeclaringType); + ILGenerator getGenerator = dynamicGet.GetILGenerator(); + + getGenerator.Emit(OpCodes.Ldarg_0); + getGenerator.Emit(OpCodes.Ldfld, fieldInfo); + if (type.IsValueType) + getGenerator.Emit(OpCodes.Box, type); + getGenerator.Emit(OpCodes.Ret); + + return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler)); + #else + return delegate(object instance) { return fieldInfo.GetValue(instance); }; + #endif + } + + static SetHandler CreateSetHandler(FieldInfo fieldInfo) + { + if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral) + return null; + #if SIMPLE_JSON_REFLECTIONEMIT + Type type = fieldInfo.FieldType; + DynamicMethod dynamicSet = CreateDynamicMethod("Set" + fieldInfo.Name, null, new Type[] { typeof(object), typeof(object) }, fieldInfo.DeclaringType); + ILGenerator setGenerator = dynamicSet.GetILGenerator(); + + setGenerator.Emit(OpCodes.Ldarg_0); + setGenerator.Emit(OpCodes.Ldarg_1); + if (type.IsValueType) + setGenerator.Emit(OpCodes.Unbox_Any, type); + setGenerator.Emit(OpCodes.Stfld, fieldInfo); + setGenerator.Emit(OpCodes.Ret); + + return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler)); + #else + return delegate(object instance, object value) { fieldInfo.SetValue(instance, value); }; + #endif + } + + static GetHandler CreateGetHandler(PropertyInfo propertyInfo) + { + #if NETFX_CORE + MethodInfo getMethodInfo = propertyInfo.GetMethod; + #else + MethodInfo getMethodInfo = propertyInfo.GetGetMethod(true); + #endif + if (getMethodInfo == null) + return null; + #if SIMPLE_JSON_REFLECTIONEMIT + Type type = propertyInfo.PropertyType; + DynamicMethod dynamicGet = CreateDynamicMethod("Get" + propertyInfo.Name, propertyInfo.DeclaringType, new Type[] { typeof(object) }, propertyInfo.DeclaringType); + ILGenerator getGenerator = dynamicGet.GetILGenerator(); + + getGenerator.Emit(OpCodes.Ldarg_0); + getGenerator.Emit(OpCodes.Call, getMethodInfo); + if (type.IsValueType) + getGenerator.Emit(OpCodes.Box, type); + getGenerator.Emit(OpCodes.Ret); + + return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler)); + #else + #if NETFX_CORE + return delegate(object instance) { return getMethodInfo.Invoke(instance, new Type[] { }); }; + #else + return delegate(object instance) { return getMethodInfo.Invoke(instance, Type.EmptyTypes); }; + #endif + #endif + } + + static SetHandler CreateSetHandler(PropertyInfo propertyInfo) + { + #if NETFX_CORE + MethodInfo setMethodInfo = propertyInfo.SetMethod; + #else + MethodInfo setMethodInfo = propertyInfo.GetSetMethod(true); + #endif + if (setMethodInfo == null) + return null; + #if SIMPLE_JSON_REFLECTIONEMIT + Type type = propertyInfo.PropertyType; + DynamicMethod dynamicSet = CreateDynamicMethod("Set" + propertyInfo.Name, null, new Type[] { typeof(object), typeof(object) }, propertyInfo.DeclaringType); + ILGenerator setGenerator = dynamicSet.GetILGenerator(); + + setGenerator.Emit(OpCodes.Ldarg_0); + setGenerator.Emit(OpCodes.Ldarg_1); + if (type.IsValueType) + setGenerator.Emit(OpCodes.Unbox_Any, type); + setGenerator.Emit(OpCodes.Call, setMethodInfo); + setGenerator.Emit(OpCodes.Ret); + return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler)); + #else + return delegate(object instance, object value) { setMethodInfo.Invoke(instance, new[] { value }); }; + #endif + } + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + sealed class MemberMap + { + public readonly MemberInfo MemberInfo; + public readonly Type Type; + public readonly GetHandler Getter; + public readonly SetHandler Setter; + + public MemberMap(PropertyInfo propertyInfo) + { + MemberInfo = propertyInfo; + Type = propertyInfo.PropertyType; + Getter = CreateGetHandler(propertyInfo); + Setter = CreateSetHandler(propertyInfo); + } + + public MemberMap(FieldInfo fieldInfo) + { + MemberInfo = fieldInfo; + Type = fieldInfo.FieldType; + Getter = CreateGetHandler(fieldInfo); + Setter = CreateSetHandler(fieldInfo); + } + } + } + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class SafeDictionary + { + private readonly object _padlock = new object(); + private readonly Dictionary _dictionary = new Dictionary(); + + public bool TryGetValue(TKey key, out TValue value) + { + return _dictionary.TryGetValue(key, out value); + } + + public TValue this[TKey key] + { + get { return _dictionary[key]; } + } + + public IEnumerator> GetEnumerator() + { + return ((ICollection>)_dictionary).GetEnumerator(); + } + + public void Add(TKey key, TValue value) + { + lock (_padlock) + { + if (_dictionary.ContainsKey(key) == false) + _dictionary.Add(key, value); + } + } + } + } + + #endregion + } diff --git a/csharp/NPitaya/src/Utils/Utils.cs b/csharp/NPitaya/src/Utils/Utils.cs new file mode 100644 index 00000000..1cff1d55 --- /dev/null +++ b/csharp/NPitaya/src/Utils/Utils.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using Google.Protobuf; +using NPitaya.Models; + +namespace NPitaya.Utils { + + public static class Utils { + + public static string DefaultRemoteNameFunc(string methodName) + { + var name = methodName; + if (name != string.Empty && char.IsUpper(name[0])) + { + name = char.ToLower(name[0]) + name.Substring(1); + } + return name; + } + + public static IEnumerable GetTypesWithAttribute(Assembly assembly, Type attribute) + { + foreach (Type type in assembly.GetTypes()) + { + if (type.GetCustomAttributes(attribute, true).Length > 0) + { + yield return type; + } + } + } + + internal static Protos.Response GetErrorResponse(string code, string msg) + { + var response = new Protos.Response {Error = new Protos.Error {Code = code, Msg = msg}}; + return response; + } + + internal static IntPtr ByteArrayToIntPtr(byte[] data) + { + IntPtr ptr = Marshal.AllocHGlobal(data.Length); + Marshal.Copy(data, 0, ptr, data.Length); + return ptr; + } + + internal static T GetProtoMessageFromResponse(NPitaya.Protos.Response response) + { + var res = (IMessage) Activator.CreateInstance(typeof(T)); + res.MergeFrom(response.Data); + Logger.Debug("getProtoMsgFromResponse: got this res {0}", res); + return (T) res; + } + } + +} diff --git a/csharp/NPitaya/src/gen/Bind.cs b/csharp/NPitaya/src/gen/Bind.cs new file mode 100644 index 00000000..d7a1132d --- /dev/null +++ b/csharp/NPitaya/src/gen/Bind.cs @@ -0,0 +1,252 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: bind.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from bind.proto + public static partial class BindReflection { + + #region Descriptor + /// File descriptor for bind.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static BindReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CgpiaW5kLnByb3RvEgZwcm90b3MiIwoHQmluZE1zZxILCgN1aWQYASABKAkS", + "CwoDZmlkGAIgASgJQjxaKWdpdGh1Yi5jb20vdG9wZnJlZWdhbWVzL3BpdGF5", + "YS9wa2cvcHJvdG9zqgIOTlBpdGF5YS5Qcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.BindMsg), global::NPitaya.Protos.BindMsg.Parser, new[]{ "Uid", "Fid" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class BindMsg : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new BindMsg()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.BindReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public BindMsg() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public BindMsg(BindMsg other) : this() { + uid_ = other.uid_; + fid_ = other.fid_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public BindMsg Clone() { + return new BindMsg(this); + } + + /// Field number for the "uid" field. + public const int UidFieldNumber = 1; + private string uid_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Uid { + get { return uid_; } + set { + uid_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "fid" field. + public const int FidFieldNumber = 2; + private string fid_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Fid { + get { return fid_; } + set { + fid_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as BindMsg); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(BindMsg other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Uid != other.Uid) return false; + if (Fid != other.Fid) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Uid.Length != 0) hash ^= Uid.GetHashCode(); + if (Fid.Length != 0) hash ^= Fid.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Uid.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Uid); + } + if (Fid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Fid); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Uid.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Uid); + } + if (Fid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Fid); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Uid.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Uid); + } + if (Fid.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Fid); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(BindMsg other) { + if (other == null) { + return; + } + if (other.Uid.Length != 0) { + Uid = other.Uid; + } + if (other.Fid.Length != 0) { + Fid = other.Fid; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Uid = input.ReadString(); + break; + } + case 18: { + Fid = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Uid = input.ReadString(); + break; + } + case 18: { + Fid = input.ReadString(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/Doc.cs b/csharp/NPitaya/src/gen/Doc.cs new file mode 100644 index 00000000..0a64fce8 --- /dev/null +++ b/csharp/NPitaya/src/gen/Doc.cs @@ -0,0 +1,216 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: doc.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from doc.proto + public static partial class DocReflection { + + #region Descriptor + /// File descriptor for doc.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static DocReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cglkb2MucHJvdG8SBnByb3RvcyISCgNEb2MSCwoDZG9jGAEgASgJQjxaKWdp", + "dGh1Yi5jb20vdG9wZnJlZWdhbWVzL3BpdGF5YS9wa2cvcHJvdG9zqgIOTlBp", + "dGF5YS5Qcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Doc), global::NPitaya.Protos.Doc.Parser, new[]{ "Doc_" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Doc : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Doc()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.DocReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Doc() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Doc(Doc other) : this() { + doc_ = other.doc_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Doc Clone() { + return new Doc(this); + } + + /// Field number for the "doc" field. + public const int Doc_FieldNumber = 1; + private string doc_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Doc_ { + get { return doc_; } + set { + doc_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Doc); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Doc other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Doc_ != other.Doc_) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Doc_.Length != 0) hash ^= Doc_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Doc_.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Doc_); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Doc_.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Doc_); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Doc_.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Doc_); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Doc other) { + if (other == null) { + return; + } + if (other.Doc_.Length != 0) { + Doc_ = other.Doc_; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Doc_ = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Doc_ = input.ReadString(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/Docmsg.cs b/csharp/NPitaya/src/gen/Docmsg.cs new file mode 100644 index 00000000..c57aabc3 --- /dev/null +++ b/csharp/NPitaya/src/gen/Docmsg.cs @@ -0,0 +1,216 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: docmsg.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from docmsg.proto + public static partial class DocmsgReflection { + + #region Descriptor + /// File descriptor for docmsg.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static DocmsgReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cgxkb2Ntc2cucHJvdG8SBnByb3RvcyIbCgZEb2NNc2cSEQoJZ2V0UHJvdG9z", + "GAEgASgIQjxaKWdpdGh1Yi5jb20vdG9wZnJlZWdhbWVzL3BpdGF5YS9wa2cv", + "cHJvdG9zqgIOTlBpdGF5YS5Qcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.DocMsg), global::NPitaya.Protos.DocMsg.Parser, new[]{ "GetProtos" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class DocMsg : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DocMsg()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.DocmsgReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public DocMsg() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public DocMsg(DocMsg other) : this() { + getProtos_ = other.getProtos_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public DocMsg Clone() { + return new DocMsg(this); + } + + /// Field number for the "getProtos" field. + public const int GetProtosFieldNumber = 1; + private bool getProtos_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool GetProtos { + get { return getProtos_; } + set { + getProtos_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as DocMsg); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(DocMsg other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (GetProtos != other.GetProtos) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (GetProtos != false) hash ^= GetProtos.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (GetProtos != false) { + output.WriteRawTag(8); + output.WriteBool(GetProtos); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (GetProtos != false) { + output.WriteRawTag(8); + output.WriteBool(GetProtos); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (GetProtos != false) { + size += 1 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(DocMsg other) { + if (other == null) { + return; + } + if (other.GetProtos != false) { + GetProtos = other.GetProtos; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + GetProtos = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + GetProtos = input.ReadBool(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/Error.cs b/csharp/NPitaya/src/gen/Error.cs new file mode 100644 index 00000000..959033e1 --- /dev/null +++ b/csharp/NPitaya/src/gen/Error.cs @@ -0,0 +1,279 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: error.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from error.proto + public static partial class ErrorReflection { + + #region Descriptor + /// File descriptor for error.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static ErrorReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CgtlcnJvci5wcm90bxIGcHJvdG9zIoIBCgVFcnJvchIMCgRjb2RlGAEgASgJ", + "EgsKA21zZxgCIAEoCRItCghtZXRhZGF0YRgDIAMoCzIbLnByb3Rvcy5FcnJv", + "ci5NZXRhZGF0YUVudHJ5Gi8KDU1ldGFkYXRhRW50cnkSCwoDa2V5GAEgASgJ", + "Eg0KBXZhbHVlGAIgASgJOgI4AUI8WilnaXRodWIuY29tL3RvcGZyZWVnYW1l", + "cy9waXRheWEvcGtnL3Byb3Rvc6oCDk5QaXRheWEuUHJvdG9zYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Error), global::NPitaya.Protos.Error.Parser, new[]{ "Code", "Msg", "Metadata" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, }) + })); + } + #endregion + + } + #region Messages + public sealed partial class Error : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Error()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ErrorReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Error() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Error(Error other) : this() { + code_ = other.code_; + msg_ = other.msg_; + metadata_ = other.metadata_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Error Clone() { + return new Error(this); + } + + /// Field number for the "code" field. + public const int CodeFieldNumber = 1; + private string code_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Code { + get { return code_; } + set { + code_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "msg" field. + public const int MsgFieldNumber = 2; + private string msg_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Msg { + get { return msg_; } + set { + msg_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "metadata" field. + public const int MetadataFieldNumber = 3; + private static readonly pbc::MapField.Codec _map_metadata_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 26); + private readonly pbc::MapField metadata_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::MapField Metadata { + get { return metadata_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Error); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Error other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Code != other.Code) return false; + if (Msg != other.Msg) return false; + if (!Metadata.Equals(other.Metadata)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Code.Length != 0) hash ^= Code.GetHashCode(); + if (Msg.Length != 0) hash ^= Msg.GetHashCode(); + hash ^= Metadata.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Code.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Code); + } + if (Msg.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Msg); + } + metadata_.WriteTo(output, _map_metadata_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Code.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Code); + } + if (Msg.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Msg); + } + metadata_.WriteTo(ref output, _map_metadata_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Code.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Code); + } + if (Msg.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Msg); + } + size += metadata_.CalculateSize(_map_metadata_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Error other) { + if (other == null) { + return; + } + if (other.Code.Length != 0) { + Code = other.Code; + } + if (other.Msg.Length != 0) { + Msg = other.Msg; + } + metadata_.Add(other.metadata_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Code = input.ReadString(); + break; + } + case 18: { + Msg = input.ReadString(); + break; + } + case 26: { + metadata_.AddEntriesFrom(input, _map_metadata_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Code = input.ReadString(); + break; + } + case 18: { + Msg = input.ReadString(); + break; + } + case 26: { + metadata_.AddEntriesFrom(ref input, _map_metadata_codec); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/Kick.cs b/csharp/NPitaya/src/gen/Kick.cs new file mode 100644 index 00000000..c751f598 --- /dev/null +++ b/csharp/NPitaya/src/gen/Kick.cs @@ -0,0 +1,390 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: kick.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from kick.proto + public static partial class KickReflection { + + #region Descriptor + /// File descriptor for kick.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static KickReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CgpraWNrLnByb3RvEgZwcm90b3MiGQoHS2lja01zZxIOCgZ1c2VySWQYASAB", + "KAkiHAoKS2lja0Fuc3dlchIOCgZraWNrZWQYASABKAhCPFopZ2l0aHViLmNv", + "bS90b3BmcmVlZ2FtZXMvcGl0YXlhL3BrZy9wcm90b3OqAg5OUGl0YXlhLlBy", + "b3Rvc2IGcHJvdG8z")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.KickMsg), global::NPitaya.Protos.KickMsg.Parser, new[]{ "UserId" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.KickAnswer), global::NPitaya.Protos.KickAnswer.Parser, new[]{ "Kicked" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class KickMsg : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new KickMsg()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.KickReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickMsg() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickMsg(KickMsg other) : this() { + userId_ = other.userId_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickMsg Clone() { + return new KickMsg(this); + } + + /// Field number for the "userId" field. + public const int UserIdFieldNumber = 1; + private string userId_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string UserId { + get { return userId_; } + set { + userId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as KickMsg); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(KickMsg other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (UserId != other.UserId) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (UserId.Length != 0) hash ^= UserId.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (UserId.Length != 0) { + output.WriteRawTag(10); + output.WriteString(UserId); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (UserId.Length != 0) { + output.WriteRawTag(10); + output.WriteString(UserId); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (UserId.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(UserId); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(KickMsg other) { + if (other == null) { + return; + } + if (other.UserId.Length != 0) { + UserId = other.UserId; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + UserId = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + UserId = input.ReadString(); + break; + } + } + } + } + #endif + + } + + public sealed partial class KickAnswer : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new KickAnswer()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.KickReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickAnswer() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickAnswer(KickAnswer other) : this() { + kicked_ = other.kicked_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickAnswer Clone() { + return new KickAnswer(this); + } + + /// Field number for the "kicked" field. + public const int KickedFieldNumber = 1; + private bool kicked_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Kicked { + get { return kicked_; } + set { + kicked_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as KickAnswer); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(KickAnswer other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Kicked != other.Kicked) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Kicked != false) hash ^= Kicked.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Kicked != false) { + output.WriteRawTag(8); + output.WriteBool(Kicked); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Kicked != false) { + output.WriteRawTag(8); + output.WriteBool(Kicked); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Kicked != false) { + size += 1 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(KickAnswer other) { + if (other == null) { + return; + } + if (other.Kicked != false) { + Kicked = other.Kicked; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Kicked = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Kicked = input.ReadBool(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/Msg.cs b/csharp/NPitaya/src/gen/Msg.cs new file mode 100644 index 00000000..de8a0ef7 --- /dev/null +++ b/csharp/NPitaya/src/gen/Msg.cs @@ -0,0 +1,373 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: msg.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from msg.proto + public static partial class MsgReflection { + + #region Descriptor + /// File descriptor for msg.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static MsgReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cgltc2cucHJvdG8SBnByb3RvcyJcCgNNc2cSCgoCaWQYASABKAQSDQoFcm91", + "dGUYAiABKAkSDAoEZGF0YRgDIAEoDBINCgVyZXBseRgEIAEoCRIdCgR0eXBl", + "GAUgASgOMg8ucHJvdG9zLk1zZ1R5cGUqRgoHTXNnVHlwZRIOCgpNc2dSZXF1", + "ZXN0EAASDQoJTXNnTm90aWZ5EAESDwoLTXNnUmVzcG9uc2UQAhILCgdNc2dQ", + "dXNoEANCPFopZ2l0aHViLmNvbS90b3BmcmVlZ2FtZXMvcGl0YXlhL3BrZy9w", + "cm90b3OqAg5OUGl0YXlhLlByb3Rvc2IGcHJvdG8z")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::NPitaya.Protos.MsgType), }, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Msg), global::NPitaya.Protos.Msg.Parser, new[]{ "Id", "Route", "Data", "Reply", "Type" }, null, null, null, null) + })); + } + #endregion + + } + #region Enums + public enum MsgType { + [pbr::OriginalName("MsgRequest")] MsgRequest = 0, + [pbr::OriginalName("MsgNotify")] MsgNotify = 1, + [pbr::OriginalName("MsgResponse")] MsgResponse = 2, + [pbr::OriginalName("MsgPush")] MsgPush = 3, + } + + #endregion + + #region Messages + public sealed partial class Msg : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Msg()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.MsgReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Msg() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Msg(Msg other) : this() { + id_ = other.id_; + route_ = other.route_; + data_ = other.data_; + reply_ = other.reply_; + type_ = other.type_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Msg Clone() { + return new Msg(this); + } + + /// Field number for the "id" field. + public const int IdFieldNumber = 1; + private ulong id_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ulong Id { + get { return id_; } + set { + id_ = value; + } + } + + /// Field number for the "route" field. + public const int RouteFieldNumber = 2; + private string route_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Route { + get { return route_; } + set { + route_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 3; + private pb::ByteString data_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Data { + get { return data_; } + set { + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "reply" field. + public const int ReplyFieldNumber = 4; + private string reply_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Reply { + get { return reply_; } + set { + reply_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "type" field. + public const int TypeFieldNumber = 5; + private global::NPitaya.Protos.MsgType type_ = global::NPitaya.Protos.MsgType.MsgRequest; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.MsgType Type { + get { return type_; } + set { + type_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Msg); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Msg other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Id != other.Id) return false; + if (Route != other.Route) return false; + if (Data != other.Data) return false; + if (Reply != other.Reply) return false; + if (Type != other.Type) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Id != 0UL) hash ^= Id.GetHashCode(); + if (Route.Length != 0) hash ^= Route.GetHashCode(); + if (Data.Length != 0) hash ^= Data.GetHashCode(); + if (Reply.Length != 0) hash ^= Reply.GetHashCode(); + if (Type != global::NPitaya.Protos.MsgType.MsgRequest) hash ^= Type.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Id != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(Id); + } + if (Route.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Route); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (Reply.Length != 0) { + output.WriteRawTag(34); + output.WriteString(Reply); + } + if (Type != global::NPitaya.Protos.MsgType.MsgRequest) { + output.WriteRawTag(40); + output.WriteEnum((int) Type); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Id != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(Id); + } + if (Route.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Route); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (Reply.Length != 0) { + output.WriteRawTag(34); + output.WriteString(Reply); + } + if (Type != global::NPitaya.Protos.MsgType.MsgRequest) { + output.WriteRawTag(40); + output.WriteEnum((int) Type); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Id != 0UL) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Id); + } + if (Route.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Route); + } + if (Data.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); + } + if (Reply.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Reply); + } + if (Type != global::NPitaya.Protos.MsgType.MsgRequest) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Msg other) { + if (other == null) { + return; + } + if (other.Id != 0UL) { + Id = other.Id; + } + if (other.Route.Length != 0) { + Route = other.Route; + } + if (other.Data.Length != 0) { + Data = other.Data; + } + if (other.Reply.Length != 0) { + Reply = other.Reply; + } + if (other.Type != global::NPitaya.Protos.MsgType.MsgRequest) { + Type = other.Type; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Id = input.ReadUInt64(); + break; + } + case 18: { + Route = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + case 34: { + Reply = input.ReadString(); + break; + } + case 40: { + Type = (global::NPitaya.Protos.MsgType) input.ReadEnum(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Id = input.ReadUInt64(); + break; + } + case 18: { + Route = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + case 34: { + Reply = input.ReadString(); + break; + } + case 40: { + Type = (global::NPitaya.Protos.MsgType) input.ReadEnum(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/Pitaya.cs b/csharp/NPitaya/src/gen/Pitaya.cs new file mode 100644 index 00000000..43a64c75 --- /dev/null +++ b/csharp/NPitaya/src/gen/Pitaya.cs @@ -0,0 +1,45 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: pitaya.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from pitaya.proto + public static partial class PitayaReflection { + + #region Descriptor + /// File descriptor for pitaya.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static PitayaReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CgxwaXRheWEucHJvdG8SBnByb3RvcxoNcmVxdWVzdC5wcm90bxoOcmVzcG9u", + "c2UucHJvdG8aCnB1c2gucHJvdG8aCmJpbmQucHJvdG8aCmtpY2sucHJvdG8y", + "0gEKBlBpdGF5YRIrCgRDYWxsEg8ucHJvdG9zLlJlcXVlc3QaEC5wcm90b3Mu", + "UmVzcG9uc2UiABIuCgpQdXNoVG9Vc2VyEgwucHJvdG9zLlB1c2gaEC5wcm90", + "b3MuUmVzcG9uc2UiABI4ChFTZXNzaW9uQmluZFJlbW90ZRIPLnByb3Rvcy5C", + "aW5kTXNnGhAucHJvdG9zLlJlc3BvbnNlIgASMQoIS2lja1VzZXISDy5wcm90", + "b3MuS2lja01zZxoSLnByb3Rvcy5LaWNrQW5zd2VyIgBCPFopZ2l0aHViLmNv", + "bS90b3BmcmVlZ2FtZXMvcGl0YXlhL3BrZy9wcm90b3OqAg5OUGl0YXlhLlBy", + "b3Rvc2IGcHJvdG8z")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::NPitaya.Protos.RequestReflection.Descriptor, global::NPitaya.Protos.ResponseReflection.Descriptor, global::NPitaya.Protos.PushReflection.Descriptor, global::NPitaya.Protos.BindReflection.Descriptor, global::NPitaya.Protos.KickReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(null, null, null)); + } + #endregion + + } +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/PitayaGrpc.cs b/csharp/NPitaya/src/gen/PitayaGrpc.cs new file mode 100644 index 00000000..adc61b18 --- /dev/null +++ b/csharp/NPitaya/src/gen/PitayaGrpc.cs @@ -0,0 +1,231 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: pitaya.proto +// +#pragma warning disable 0414, 1591 +#region Designer generated code + +using grpc = global::Grpc.Core; + +namespace NPitaya.Protos { + public static partial class Pitaya + { + static readonly string __ServiceName = "protos.Pitaya"; + + static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context) + { + #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION + if (message is global::Google.Protobuf.IBufferMessage) + { + context.SetPayloadLength(message.CalculateSize()); + global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter()); + context.Complete(); + return; + } + #endif + context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message)); + } + + static class __Helper_MessageCache + { + public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T)); + } + + static T __Helper_DeserializeMessage(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser parser) where T : global::Google.Protobuf.IMessage + { + #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION + if (__Helper_MessageCache.IsBufferMessage) + { + return parser.ParseFrom(context.PayloadAsReadOnlySequence()); + } + #endif + return parser.ParseFrom(context.PayloadAsNewBuffer()); + } + + static readonly grpc::Marshaller __Marshaller_protos_Request = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Request.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_Response = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Response.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_Push = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Push.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_BindMsg = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.BindMsg.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_KickMsg = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.KickMsg.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_KickAnswer = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.KickAnswer.Parser)); + + static readonly grpc::Method __Method_Call = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "Call", + __Marshaller_protos_Request, + __Marshaller_protos_Response); + + static readonly grpc::Method __Method_PushToUser = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "PushToUser", + __Marshaller_protos_Push, + __Marshaller_protos_Response); + + static readonly grpc::Method __Method_SessionBindRemote = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "SessionBindRemote", + __Marshaller_protos_BindMsg, + __Marshaller_protos_Response); + + static readonly grpc::Method __Method_KickUser = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "KickUser", + __Marshaller_protos_KickMsg, + __Marshaller_protos_KickAnswer); + + /// Service descriptor + public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor + { + get { return global::NPitaya.Protos.PitayaReflection.Descriptor.Services[0]; } + } + + /// Base class for server-side implementations of Pitaya + [grpc::BindServiceMethod(typeof(Pitaya), "BindService")] + public abstract partial class PitayaBase + { + public virtual global::System.Threading.Tasks.Task Call(global::NPitaya.Protos.Request request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task PushToUser(global::NPitaya.Protos.Push request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task SessionBindRemote(global::NPitaya.Protos.BindMsg request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task KickUser(global::NPitaya.Protos.KickMsg request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + } + + /// Client for Pitaya + public partial class PitayaClient : grpc::ClientBase + { + /// Creates a new client for Pitaya + /// The channel to use to make remote calls. + public PitayaClient(grpc::ChannelBase channel) : base(channel) + { + } + /// Creates a new client for Pitaya that uses a custom CallInvoker. + /// The callInvoker to use to make remote calls. + public PitayaClient(grpc::CallInvoker callInvoker) : base(callInvoker) + { + } + /// Protected parameterless constructor to allow creation of test doubles. + protected PitayaClient() : base() + { + } + /// Protected constructor to allow creation of configured clients. + /// The client configuration. + protected PitayaClient(ClientBaseConfiguration configuration) : base(configuration) + { + } + + public virtual global::NPitaya.Protos.Response Call(global::NPitaya.Protos.Request request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return Call(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Response Call(global::NPitaya.Protos.Request request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_Call, null, options, request); + } + public virtual grpc::AsyncUnaryCall CallAsync(global::NPitaya.Protos.Request request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return CallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall CallAsync(global::NPitaya.Protos.Request request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_Call, null, options, request); + } + public virtual global::NPitaya.Protos.Response PushToUser(global::NPitaya.Protos.Push request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return PushToUser(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Response PushToUser(global::NPitaya.Protos.Push request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_PushToUser, null, options, request); + } + public virtual grpc::AsyncUnaryCall PushToUserAsync(global::NPitaya.Protos.Push request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return PushToUserAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall PushToUserAsync(global::NPitaya.Protos.Push request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_PushToUser, null, options, request); + } + public virtual global::NPitaya.Protos.Response SessionBindRemote(global::NPitaya.Protos.BindMsg request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SessionBindRemote(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Response SessionBindRemote(global::NPitaya.Protos.BindMsg request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_SessionBindRemote, null, options, request); + } + public virtual grpc::AsyncUnaryCall SessionBindRemoteAsync(global::NPitaya.Protos.BindMsg request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SessionBindRemoteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall SessionBindRemoteAsync(global::NPitaya.Protos.BindMsg request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_SessionBindRemote, null, options, request); + } + public virtual global::NPitaya.Protos.KickAnswer KickUser(global::NPitaya.Protos.KickMsg request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return KickUser(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.KickAnswer KickUser(global::NPitaya.Protos.KickMsg request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_KickUser, null, options, request); + } + public virtual grpc::AsyncUnaryCall KickUserAsync(global::NPitaya.Protos.KickMsg request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return KickUserAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall KickUserAsync(global::NPitaya.Protos.KickMsg request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_KickUser, null, options, request); + } + /// Creates a new instance of client from given ClientBaseConfiguration. + protected override PitayaClient NewInstance(ClientBaseConfiguration configuration) + { + return new PitayaClient(configuration); + } + } + + /// Creates service definition that can be registered with a server + /// An object implementing the server-side handling logic. + public static grpc::ServerServiceDefinition BindService(PitayaBase serviceImpl) + { + return grpc::ServerServiceDefinition.CreateBuilder() + .AddMethod(__Method_Call, serviceImpl.Call) + .AddMethod(__Method_PushToUser, serviceImpl.PushToUser) + .AddMethod(__Method_SessionBindRemote, serviceImpl.SessionBindRemote) + .AddMethod(__Method_KickUser, serviceImpl.KickUser).Build(); + } + + /// Register service method with a service binder with or without implementation. Useful when customizing the service binding logic. + /// Note: this method is part of an experimental API that can change or be removed without any prior notice. + /// Service methods will be bound by calling AddMethod on this object. + /// An object implementing the server-side handling logic. + public static void BindService(grpc::ServiceBinderBase serviceBinder, PitayaBase serviceImpl) + { + serviceBinder.AddMethod(__Method_Call, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.Call)); + serviceBinder.AddMethod(__Method_PushToUser, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.PushToUser)); + serviceBinder.AddMethod(__Method_SessionBindRemote, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.SessionBindRemote)); + serviceBinder.AddMethod(__Method_KickUser, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.KickUser)); + } + + } +} +#endregion diff --git a/csharp/NPitaya/src/gen/Protodescriptor.cs b/csharp/NPitaya/src/gen/Protodescriptor.cs new file mode 100644 index 00000000..3a6d60b3 --- /dev/null +++ b/csharp/NPitaya/src/gen/Protodescriptor.cs @@ -0,0 +1,718 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: protodescriptor.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from protodescriptor.proto + public static partial class ProtodescriptorReflection { + + #region Descriptor + /// File descriptor for protodescriptor.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static ProtodescriptorReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChVwcm90b2Rlc2NyaXB0b3IucHJvdG8SBnByb3RvcyIfCg9Qcm90b0Rlc2Ny", + "aXB0b3ISDAoEZGVzYxgBIAEoDCIZCglQcm90b05hbWUSDAoEbmFtZRgBIAEo", + "CSIgChBQcm90b0Rlc2NyaXB0b3JzEgwKBGRlc2MYASADKAwiGgoKUHJvdG9O", + "YW1lcxIMCgRuYW1lGAEgAygJQjxaKWdpdGh1Yi5jb20vdG9wZnJlZWdhbWVz", + "L3BpdGF5YS9wa2cvcHJvdG9zqgIOTlBpdGF5YS5Qcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.ProtoDescriptor), global::NPitaya.Protos.ProtoDescriptor.Parser, new[]{ "Desc" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.ProtoName), global::NPitaya.Protos.ProtoName.Parser, new[]{ "Name" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.ProtoDescriptors), global::NPitaya.Protos.ProtoDescriptors.Parser, new[]{ "Desc" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.ProtoNames), global::NPitaya.Protos.ProtoNames.Parser, new[]{ "Name" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + /// + /// Descriptor proto used to retrieve zipped proto descriptors remotely + /// + public sealed partial class ProtoDescriptor : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ProtoDescriptor()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ProtodescriptorReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptor() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptor(ProtoDescriptor other) : this() { + desc_ = other.desc_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptor Clone() { + return new ProtoDescriptor(this); + } + + /// Field number for the "desc" field. + public const int DescFieldNumber = 1; + private pb::ByteString desc_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Desc { + get { return desc_; } + set { + desc_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as ProtoDescriptor); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(ProtoDescriptor other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Desc != other.Desc) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Desc.Length != 0) hash ^= Desc.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Desc.Length != 0) { + output.WriteRawTag(10); + output.WriteBytes(Desc); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Desc.Length != 0) { + output.WriteRawTag(10); + output.WriteBytes(Desc); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Desc.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Desc); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(ProtoDescriptor other) { + if (other == null) { + return; + } + if (other.Desc.Length != 0) { + Desc = other.Desc; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Desc = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Desc = input.ReadBytes(); + break; + } + } + } + } + #endif + + } + + public sealed partial class ProtoName : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ProtoName()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ProtodescriptorReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoName() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoName(ProtoName other) : this() { + name_ = other.name_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoName Clone() { + return new ProtoName(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private string name_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Name { + get { return name_; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as ProtoName); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(ProtoName other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(ProtoName other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Name = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Name = input.ReadString(); + break; + } + } + } + } + #endif + + } + + public sealed partial class ProtoDescriptors : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ProtoDescriptors()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ProtodescriptorReflection.Descriptor.MessageTypes[2]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptors() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptors(ProtoDescriptors other) : this() { + desc_ = other.desc_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptors Clone() { + return new ProtoDescriptors(this); + } + + /// Field number for the "desc" field. + public const int DescFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_desc_codec + = pb::FieldCodec.ForBytes(10); + private readonly pbc::RepeatedField desc_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::RepeatedField Desc { + get { return desc_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as ProtoDescriptors); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(ProtoDescriptors other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!desc_.Equals(other.desc_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + hash ^= desc_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + desc_.WriteTo(output, _repeated_desc_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + desc_.WriteTo(ref output, _repeated_desc_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + size += desc_.CalculateSize(_repeated_desc_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(ProtoDescriptors other) { + if (other == null) { + return; + } + desc_.Add(other.desc_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + desc_.AddEntriesFrom(input, _repeated_desc_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + desc_.AddEntriesFrom(ref input, _repeated_desc_codec); + break; + } + } + } + } + #endif + + } + + public sealed partial class ProtoNames : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ProtoNames()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ProtodescriptorReflection.Descriptor.MessageTypes[3]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoNames() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoNames(ProtoNames other) : this() { + name_ = other.name_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoNames Clone() { + return new ProtoNames(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_name_codec + = pb::FieldCodec.ForString(10); + private readonly pbc::RepeatedField name_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::RepeatedField Name { + get { return name_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as ProtoNames); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(ProtoNames other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!name_.Equals(other.name_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + hash ^= name_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + name_.WriteTo(output, _repeated_name_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + name_.WriteTo(ref output, _repeated_name_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + size += name_.CalculateSize(_repeated_name_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(ProtoNames other) { + if (other == null) { + return; + } + name_.Add(other.name_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + name_.AddEntriesFrom(input, _repeated_name_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + name_.AddEntriesFrom(ref input, _repeated_name_codec); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/Push.cs b/csharp/NPitaya/src/gen/Push.cs new file mode 100644 index 00000000..3f9f7620 --- /dev/null +++ b/csharp/NPitaya/src/gen/Push.cs @@ -0,0 +1,289 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: push.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from push.proto + public static partial class PushReflection { + + #region Descriptor + /// File descriptor for push.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static PushReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CgpwdXNoLnByb3RvEgZwcm90b3MiMAoEUHVzaBINCgVyb3V0ZRgBIAEoCRIL", + "CgN1aWQYAiABKAkSDAoEZGF0YRgDIAEoDEI8WilnaXRodWIuY29tL3RvcGZy", + "ZWVnYW1lcy9waXRheWEvcGtnL3Byb3Rvc6oCDk5QaXRheWEuUHJvdG9zYgZw", + "cm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Push), global::NPitaya.Protos.Push.Parser, new[]{ "Route", "Uid", "Data" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Push : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Push()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.PushReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Push() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Push(Push other) : this() { + route_ = other.route_; + uid_ = other.uid_; + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Push Clone() { + return new Push(this); + } + + /// Field number for the "route" field. + public const int RouteFieldNumber = 1; + private string route_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Route { + get { return route_; } + set { + route_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "uid" field. + public const int UidFieldNumber = 2; + private string uid_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Uid { + get { return uid_; } + set { + uid_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 3; + private pb::ByteString data_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Data { + get { return data_; } + set { + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Push); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Push other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Route != other.Route) return false; + if (Uid != other.Uid) return false; + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Route.Length != 0) hash ^= Route.GetHashCode(); + if (Uid.Length != 0) hash ^= Uid.GetHashCode(); + if (Data.Length != 0) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Route.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Route); + } + if (Uid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Uid); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Route.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Route); + } + if (Uid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Uid); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Route.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Route); + } + if (Uid.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Uid); + } + if (Data.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Push other) { + if (other == null) { + return; + } + if (other.Route.Length != 0) { + Route = other.Route; + } + if (other.Uid.Length != 0) { + Uid = other.Uid; + } + if (other.Data.Length != 0) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Route = input.ReadString(); + break; + } + case 18: { + Uid = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Route = input.ReadString(); + break; + } + case 18: { + Uid = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/Request.cs b/csharp/NPitaya/src/gen/Request.cs new file mode 100644 index 00000000..fbed59f9 --- /dev/null +++ b/csharp/NPitaya/src/gen/Request.cs @@ -0,0 +1,390 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: request.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from request.proto + public static partial class RequestReflection { + + #region Descriptor + /// File descriptor for request.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static RequestReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cg1yZXF1ZXN0LnByb3RvEgZwcm90b3MaDXNlc3Npb24ucHJvdG8aCW1zZy5w", + "cm90byKKAQoHUmVxdWVzdBIdCgR0eXBlGAEgASgOMg8ucHJvdG9zLlJQQ1R5", + "cGUSIAoHc2Vzc2lvbhgCIAEoCzIPLnByb3Rvcy5TZXNzaW9uEhgKA21zZxgD", + "IAEoCzILLnByb3Rvcy5Nc2cSEgoKZnJvbnRlbmRJRBgEIAEoCRIQCghtZXRh", + "ZGF0YRgFIAEoDCocCgdSUENUeXBlEgcKA1N5cxAAEggKBFVzZXIQAUI8Wiln", + "aXRodWIuY29tL3RvcGZyZWVnYW1lcy9waXRheWEvcGtnL3Byb3Rvc6oCDk5Q", + "aXRheWEuUHJvdG9zYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::NPitaya.Protos.SessionReflection.Descriptor, global::NPitaya.Protos.MsgReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::NPitaya.Protos.RPCType), }, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Request), global::NPitaya.Protos.Request.Parser, new[]{ "Type", "Session", "Msg", "FrontendID", "Metadata" }, null, null, null, null) + })); + } + #endregion + + } + #region Enums + public enum RPCType { + [pbr::OriginalName("Sys")] Sys = 0, + [pbr::OriginalName("User")] User = 1, + } + + #endregion + + #region Messages + public sealed partial class Request : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Request()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.RequestReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Request() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Request(Request other) : this() { + type_ = other.type_; + session_ = other.session_ != null ? other.session_.Clone() : null; + msg_ = other.msg_ != null ? other.msg_.Clone() : null; + frontendID_ = other.frontendID_; + metadata_ = other.metadata_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Request Clone() { + return new Request(this); + } + + /// Field number for the "type" field. + public const int TypeFieldNumber = 1; + private global::NPitaya.Protos.RPCType type_ = global::NPitaya.Protos.RPCType.Sys; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.RPCType Type { + get { return type_; } + set { + type_ = value; + } + } + + /// Field number for the "session" field. + public const int SessionFieldNumber = 2; + private global::NPitaya.Protos.Session session_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Session Session { + get { return session_; } + set { + session_ = value; + } + } + + /// Field number for the "msg" field. + public const int MsgFieldNumber = 3; + private global::NPitaya.Protos.Msg msg_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Msg Msg { + get { return msg_; } + set { + msg_ = value; + } + } + + /// Field number for the "frontendID" field. + public const int FrontendIDFieldNumber = 4; + private string frontendID_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string FrontendID { + get { return frontendID_; } + set { + frontendID_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "metadata" field. + public const int MetadataFieldNumber = 5; + private pb::ByteString metadata_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Metadata { + get { return metadata_; } + set { + metadata_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Request); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Request other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Type != other.Type) return false; + if (!object.Equals(Session, other.Session)) return false; + if (!object.Equals(Msg, other.Msg)) return false; + if (FrontendID != other.FrontendID) return false; + if (Metadata != other.Metadata) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Type != global::NPitaya.Protos.RPCType.Sys) hash ^= Type.GetHashCode(); + if (session_ != null) hash ^= Session.GetHashCode(); + if (msg_ != null) hash ^= Msg.GetHashCode(); + if (FrontendID.Length != 0) hash ^= FrontendID.GetHashCode(); + if (Metadata.Length != 0) hash ^= Metadata.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Type != global::NPitaya.Protos.RPCType.Sys) { + output.WriteRawTag(8); + output.WriteEnum((int) Type); + } + if (session_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Session); + } + if (msg_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Msg); + } + if (FrontendID.Length != 0) { + output.WriteRawTag(34); + output.WriteString(FrontendID); + } + if (Metadata.Length != 0) { + output.WriteRawTag(42); + output.WriteBytes(Metadata); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Type != global::NPitaya.Protos.RPCType.Sys) { + output.WriteRawTag(8); + output.WriteEnum((int) Type); + } + if (session_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Session); + } + if (msg_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Msg); + } + if (FrontendID.Length != 0) { + output.WriteRawTag(34); + output.WriteString(FrontendID); + } + if (Metadata.Length != 0) { + output.WriteRawTag(42); + output.WriteBytes(Metadata); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Type != global::NPitaya.Protos.RPCType.Sys) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); + } + if (session_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Session); + } + if (msg_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Msg); + } + if (FrontendID.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FrontendID); + } + if (Metadata.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Metadata); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Request other) { + if (other == null) { + return; + } + if (other.Type != global::NPitaya.Protos.RPCType.Sys) { + Type = other.Type; + } + if (other.session_ != null) { + if (session_ == null) { + Session = new global::NPitaya.Protos.Session(); + } + Session.MergeFrom(other.Session); + } + if (other.msg_ != null) { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + Msg.MergeFrom(other.Msg); + } + if (other.FrontendID.Length != 0) { + FrontendID = other.FrontendID; + } + if (other.Metadata.Length != 0) { + Metadata = other.Metadata; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Type = (global::NPitaya.Protos.RPCType) input.ReadEnum(); + break; + } + case 18: { + if (session_ == null) { + Session = new global::NPitaya.Protos.Session(); + } + input.ReadMessage(Session); + break; + } + case 26: { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + input.ReadMessage(Msg); + break; + } + case 34: { + FrontendID = input.ReadString(); + break; + } + case 42: { + Metadata = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Type = (global::NPitaya.Protos.RPCType) input.ReadEnum(); + break; + } + case 18: { + if (session_ == null) { + Session = new global::NPitaya.Protos.Session(); + } + input.ReadMessage(Session); + break; + } + case 26: { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + input.ReadMessage(Msg); + break; + } + case 34: { + FrontendID = input.ReadString(); + break; + } + case 42: { + Metadata = input.ReadBytes(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/Response.cs b/csharp/NPitaya/src/gen/Response.cs new file mode 100644 index 00000000..2882156c --- /dev/null +++ b/csharp/NPitaya/src/gen/Response.cs @@ -0,0 +1,262 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: response.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from response.proto + public static partial class ResponseReflection { + + #region Descriptor + /// File descriptor for response.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static ResponseReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cg5yZXNwb25zZS5wcm90bxIGcHJvdG9zGgtlcnJvci5wcm90byI2CghSZXNw", + "b25zZRIMCgRkYXRhGAEgASgMEhwKBWVycm9yGAIgASgLMg0ucHJvdG9zLkVy", + "cm9yQjxaKWdpdGh1Yi5jb20vdG9wZnJlZWdhbWVzL3BpdGF5YS9wa2cvcHJv", + "dG9zqgIOTlBpdGF5YS5Qcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::NPitaya.Protos.ErrorReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Response), global::NPitaya.Protos.Response.Parser, new[]{ "Data", "Error" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Response : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Response()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ResponseReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Response() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Response(Response other) : this() { + data_ = other.data_; + error_ = other.error_ != null ? other.error_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Response Clone() { + return new Response(this); + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 1; + private pb::ByteString data_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Data { + get { return data_; } + set { + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "error" field. + public const int ErrorFieldNumber = 2; + private global::NPitaya.Protos.Error error_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Error Error { + get { return error_; } + set { + error_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Response); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Response other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Data != other.Data) return false; + if (!object.Equals(Error, other.Error)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Data.Length != 0) hash ^= Data.GetHashCode(); + if (error_ != null) hash ^= Error.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Data.Length != 0) { + output.WriteRawTag(10); + output.WriteBytes(Data); + } + if (error_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Error); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Data.Length != 0) { + output.WriteRawTag(10); + output.WriteBytes(Data); + } + if (error_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Error); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Data.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); + } + if (error_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Error); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Response other) { + if (other == null) { + return; + } + if (other.Data.Length != 0) { + Data = other.Data; + } + if (other.error_ != null) { + if (error_ == null) { + Error = new global::NPitaya.Protos.Error(); + } + Error.MergeFrom(other.Error); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Data = input.ReadBytes(); + break; + } + case 18: { + if (error_ == null) { + Error = new global::NPitaya.Protos.Error(); + } + input.ReadMessage(Error); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Data = input.ReadBytes(); + break; + } + case 18: { + if (error_ == null) { + Error = new global::NPitaya.Protos.Error(); + } + input.ReadMessage(Error); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/Session.cs b/csharp/NPitaya/src/gen/Session.cs new file mode 100644 index 00000000..7fd84830 --- /dev/null +++ b/csharp/NPitaya/src/gen/Session.cs @@ -0,0 +1,289 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: session.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from session.proto + public static partial class SessionReflection { + + #region Descriptor + /// File descriptor for session.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static SessionReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cg1zZXNzaW9uLnByb3RvEgZwcm90b3MiMAoHU2Vzc2lvbhIKCgJpZBgBIAEo", + "AxILCgN1aWQYAiABKAkSDAoEZGF0YRgDIAEoDEI8WilnaXRodWIuY29tL3Rv", + "cGZyZWVnYW1lcy9waXRheWEvcGtnL3Byb3Rvc6oCDk5QaXRheWEuUHJvdG9z", + "YgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Session), global::NPitaya.Protos.Session.Parser, new[]{ "Id", "Uid", "Data" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Session : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Session()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SessionReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Session() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Session(Session other) : this() { + id_ = other.id_; + uid_ = other.uid_; + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Session Clone() { + return new Session(this); + } + + /// Field number for the "id" field. + public const int IdFieldNumber = 1; + private long id_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public long Id { + get { return id_; } + set { + id_ = value; + } + } + + /// Field number for the "uid" field. + public const int UidFieldNumber = 2; + private string uid_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Uid { + get { return uid_; } + set { + uid_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 3; + private pb::ByteString data_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Data { + get { return data_; } + set { + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Session); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Session other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Id != other.Id) return false; + if (Uid != other.Uid) return false; + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Id != 0L) hash ^= Id.GetHashCode(); + if (Uid.Length != 0) hash ^= Uid.GetHashCode(); + if (Data.Length != 0) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Id != 0L) { + output.WriteRawTag(8); + output.WriteInt64(Id); + } + if (Uid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Uid); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Id != 0L) { + output.WriteRawTag(8); + output.WriteInt64(Id); + } + if (Uid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Uid); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Id != 0L) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(Id); + } + if (Uid.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Uid); + } + if (Data.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Session other) { + if (other == null) { + return; + } + if (other.Id != 0L) { + Id = other.Id; + } + if (other.Uid.Length != 0) { + Uid = other.Uid; + } + if (other.Data.Length != 0) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Id = input.ReadInt64(); + break; + } + case 18: { + Uid = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Id = input.ReadInt64(); + break; + } + case 18: { + Uid = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/Sidecar.cs b/csharp/NPitaya/src/gen/Sidecar.cs new file mode 100644 index 00000000..9e0d35bb --- /dev/null +++ b/csharp/NPitaya/src/gen/Sidecar.cs @@ -0,0 +1,2200 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: sidecar.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from sidecar.proto + public static partial class SidecarReflection { + + #region Descriptor + /// File descriptor for sidecar.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static SidecarReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cg1zaWRlY2FyLnByb3RvEgZwcm90b3MaC2Vycm9yLnByb3RvGgpwdXNoLnBy", + "b3RvGgpraWNrLnByb3RvGgltc2cucHJvdG8aDnJlc3BvbnNlLnByb3RvGg1y", + "ZXF1ZXN0LnByb3RvGhtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8ipwEK", + "BlNlcnZlchIKCgJpZBgBIAEoCRIQCghmcm9udGVuZBgCIAEoCBIMCgR0eXBl", + "GAMgASgJEi4KCG1ldGFkYXRhGAQgAygLMhwucHJvdG9zLlNlcnZlci5NZXRh", + "ZGF0YUVudHJ5EhAKCGhvc3RuYW1lGAUgASgJGi8KDU1ldGFkYXRhRW50cnkS", + "CwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASJtCgdTREV2ZW50EiQK", + "BWV2ZW50GAEgASgOMhUucHJvdG9zLlNERXZlbnQuRXZlbnQSHgoGc2VydmVy", + "GAIgASgLMg4ucHJvdG9zLlNlcnZlciIcCgVFdmVudBIHCgNBREQQABIKCgZS", + "RU1PVkUQASJmChJTdGFydFBpdGF5YVJlcXVlc3QSHgoGY29uZmlnGAEgASgL", + "Mg4ucHJvdG9zLlNlcnZlchIeChZzaG91bGRDb21wcmVzc01lc3NhZ2VzGAIg", + "ASgIEhAKCGRlYnVnTG9nGAMgASgIIjcKCVJlcXVlc3RUbxIQCghzZXJ2ZXJJ", + "RBgBIAEoCRIYCgNtc2cYAiABKAsyCy5wcm90b3MuTXNnIlcKC1JQQ1Jlc3Bv", + "bnNlEg0KBXJlcUlkGAEgASgEEh0KA3JlcxgCIAEoCzIQLnByb3Rvcy5SZXNw", + "b25zZRIaCgNlcnIYAyABKAsyDS5wcm90b3MuRXJyb3IiPQoOU2lkZWNhclJl", + "cXVlc3QSDQoFcmVxSWQYASABKAQSHAoDcmVxGAIgASgLMg8ucHJvdG9zLlJl", + "cXVlc3QiPwoLUHVzaFJlcXVlc3QSFAoMZnJvbnRlbmRUeXBlGAIgASgJEhoK", + "BHB1c2gYAyABKAsyDC5wcm90b3MuUHVzaCI1CgxQdXNoUmVzcG9uc2USEgoK", + "ZmFpbGVkVWlkcxgBIAMoCRIRCgloYXNGYWlsZWQYAiABKAgiQgoLS2lja1Jl", + "cXVlc3QSFAoMZnJvbnRlbmRUeXBlGAIgASgJEh0KBGtpY2sYAyABKAsyDy5w", + "cm90b3MuS2lja01zZzL1AwoHU2lkZWNhchIrCglHZXRTZXJ2ZXISDi5wcm90", + "b3MuU2VydmVyGg4ucHJvdG9zLlNlcnZlchI7CglIZWFydGJlYXQSFi5nb29n", + "bGUucHJvdG9idWYuRW1wdHkaFi5nb29nbGUucHJvdG9idWYuRW1wdHkSPAoJ", + "TGlzdGVuUlBDEhMucHJvdG9zLlJQQ1Jlc3BvbnNlGhYucHJvdG9zLlNpZGVj", + "YXJSZXF1ZXN0KAEwARI1CghMaXN0ZW5TRBIWLmdvb2dsZS5wcm90b2J1Zi5F", + "bXB0eRoPLnByb3Rvcy5TREV2ZW50MAESLgoHU2VuZFJQQxIRLnByb3Rvcy5S", + "ZXF1ZXN0VG8aEC5wcm90b3MuUmVzcG9uc2USNQoIU2VuZFB1c2gSEy5wcm90", + "b3MuUHVzaFJlcXVlc3QaFC5wcm90b3MuUHVzaFJlc3BvbnNlEjUKCFNlbmRL", + "aWNrEhMucHJvdG9zLktpY2tSZXF1ZXN0GhQucHJvdG9zLlB1c2hSZXNwb25z", + "ZRI4CgtTdGFydFBpdGF5YRIaLnByb3Rvcy5TdGFydFBpdGF5YVJlcXVlc3Qa", + "DS5wcm90b3MuRXJyb3ISMwoKU3RvcFBpdGF5YRIWLmdvb2dsZS5wcm90b2J1", + "Zi5FbXB0eRoNLnByb3Rvcy5FcnJvckI8WilnaXRodWIuY29tL3RvcGZyZWVn", + "YW1lcy9waXRheWEvcGtnL3Byb3Rvc6oCDk5QaXRheWEuUHJvdG9zYgZwcm90", + "bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::NPitaya.Protos.ErrorReflection.Descriptor, global::NPitaya.Protos.PushReflection.Descriptor, global::NPitaya.Protos.KickReflection.Descriptor, global::NPitaya.Protos.MsgReflection.Descriptor, global::NPitaya.Protos.ResponseReflection.Descriptor, global::NPitaya.Protos.RequestReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Server), global::NPitaya.Protos.Server.Parser, new[]{ "Id", "Frontend", "Type", "Metadata", "Hostname" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.SDEvent), global::NPitaya.Protos.SDEvent.Parser, new[]{ "Event", "Server" }, null, new[]{ typeof(global::NPitaya.Protos.SDEvent.Types.Event) }, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.StartPitayaRequest), global::NPitaya.Protos.StartPitayaRequest.Parser, new[]{ "Config", "ShouldCompressMessages", "DebugLog" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.RequestTo), global::NPitaya.Protos.RequestTo.Parser, new[]{ "ServerID", "Msg" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.RPCResponse), global::NPitaya.Protos.RPCResponse.Parser, new[]{ "ReqId", "Res", "Err" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.SidecarRequest), global::NPitaya.Protos.SidecarRequest.Parser, new[]{ "ReqId", "Req" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.PushRequest), global::NPitaya.Protos.PushRequest.Parser, new[]{ "FrontendType", "Push" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.PushResponse), global::NPitaya.Protos.PushResponse.Parser, new[]{ "FailedUids", "HasFailed" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.KickRequest), global::NPitaya.Protos.KickRequest.Parser, new[]{ "FrontendType", "Kick" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Server : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Server()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Server() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Server(Server other) : this() { + id_ = other.id_; + frontend_ = other.frontend_; + type_ = other.type_; + metadata_ = other.metadata_.Clone(); + hostname_ = other.hostname_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Server Clone() { + return new Server(this); + } + + /// Field number for the "id" field. + public const int IdFieldNumber = 1; + private string id_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Id { + get { return id_; } + set { + id_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "frontend" field. + public const int FrontendFieldNumber = 2; + private bool frontend_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Frontend { + get { return frontend_; } + set { + frontend_ = value; + } + } + + /// Field number for the "type" field. + public const int TypeFieldNumber = 3; + private string type_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Type { + get { return type_; } + set { + type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "metadata" field. + public const int MetadataFieldNumber = 4; + private static readonly pbc::MapField.Codec _map_metadata_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 34); + private readonly pbc::MapField metadata_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::MapField Metadata { + get { return metadata_; } + } + + /// Field number for the "hostname" field. + public const int HostnameFieldNumber = 5; + private string hostname_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Hostname { + get { return hostname_; } + set { + hostname_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Server); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Server other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Id != other.Id) return false; + if (Frontend != other.Frontend) return false; + if (Type != other.Type) return false; + if (!Metadata.Equals(other.Metadata)) return false; + if (Hostname != other.Hostname) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Id.Length != 0) hash ^= Id.GetHashCode(); + if (Frontend != false) hash ^= Frontend.GetHashCode(); + if (Type.Length != 0) hash ^= Type.GetHashCode(); + hash ^= Metadata.GetHashCode(); + if (Hostname.Length != 0) hash ^= Hostname.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Id.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Id); + } + if (Frontend != false) { + output.WriteRawTag(16); + output.WriteBool(Frontend); + } + if (Type.Length != 0) { + output.WriteRawTag(26); + output.WriteString(Type); + } + metadata_.WriteTo(output, _map_metadata_codec); + if (Hostname.Length != 0) { + output.WriteRawTag(42); + output.WriteString(Hostname); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Id.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Id); + } + if (Frontend != false) { + output.WriteRawTag(16); + output.WriteBool(Frontend); + } + if (Type.Length != 0) { + output.WriteRawTag(26); + output.WriteString(Type); + } + metadata_.WriteTo(ref output, _map_metadata_codec); + if (Hostname.Length != 0) { + output.WriteRawTag(42); + output.WriteString(Hostname); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Id.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Id); + } + if (Frontend != false) { + size += 1 + 1; + } + if (Type.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Type); + } + size += metadata_.CalculateSize(_map_metadata_codec); + if (Hostname.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Hostname); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Server other) { + if (other == null) { + return; + } + if (other.Id.Length != 0) { + Id = other.Id; + } + if (other.Frontend != false) { + Frontend = other.Frontend; + } + if (other.Type.Length != 0) { + Type = other.Type; + } + metadata_.Add(other.metadata_); + if (other.Hostname.Length != 0) { + Hostname = other.Hostname; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Id = input.ReadString(); + break; + } + case 16: { + Frontend = input.ReadBool(); + break; + } + case 26: { + Type = input.ReadString(); + break; + } + case 34: { + metadata_.AddEntriesFrom(input, _map_metadata_codec); + break; + } + case 42: { + Hostname = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Id = input.ReadString(); + break; + } + case 16: { + Frontend = input.ReadBool(); + break; + } + case 26: { + Type = input.ReadString(); + break; + } + case 34: { + metadata_.AddEntriesFrom(ref input, _map_metadata_codec); + break; + } + case 42: { + Hostname = input.ReadString(); + break; + } + } + } + } + #endif + + } + + public sealed partial class SDEvent : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SDEvent()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SDEvent() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SDEvent(SDEvent other) : this() { + event_ = other.event_; + server_ = other.server_ != null ? other.server_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SDEvent Clone() { + return new SDEvent(this); + } + + /// Field number for the "event" field. + public const int EventFieldNumber = 1; + private global::NPitaya.Protos.SDEvent.Types.Event event_ = global::NPitaya.Protos.SDEvent.Types.Event.Add; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.SDEvent.Types.Event Event { + get { return event_; } + set { + event_ = value; + } + } + + /// Field number for the "server" field. + public const int ServerFieldNumber = 2; + private global::NPitaya.Protos.Server server_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Server Server { + get { return server_; } + set { + server_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as SDEvent); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(SDEvent other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Event != other.Event) return false; + if (!object.Equals(Server, other.Server)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Event != global::NPitaya.Protos.SDEvent.Types.Event.Add) hash ^= Event.GetHashCode(); + if (server_ != null) hash ^= Server.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Event != global::NPitaya.Protos.SDEvent.Types.Event.Add) { + output.WriteRawTag(8); + output.WriteEnum((int) Event); + } + if (server_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Server); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Event != global::NPitaya.Protos.SDEvent.Types.Event.Add) { + output.WriteRawTag(8); + output.WriteEnum((int) Event); + } + if (server_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Server); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Event != global::NPitaya.Protos.SDEvent.Types.Event.Add) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Event); + } + if (server_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Server); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(SDEvent other) { + if (other == null) { + return; + } + if (other.Event != global::NPitaya.Protos.SDEvent.Types.Event.Add) { + Event = other.Event; + } + if (other.server_ != null) { + if (server_ == null) { + Server = new global::NPitaya.Protos.Server(); + } + Server.MergeFrom(other.Server); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Event = (global::NPitaya.Protos.SDEvent.Types.Event) input.ReadEnum(); + break; + } + case 18: { + if (server_ == null) { + Server = new global::NPitaya.Protos.Server(); + } + input.ReadMessage(Server); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Event = (global::NPitaya.Protos.SDEvent.Types.Event) input.ReadEnum(); + break; + } + case 18: { + if (server_ == null) { + Server = new global::NPitaya.Protos.Server(); + } + input.ReadMessage(Server); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the SDEvent message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static partial class Types { + public enum Event { + [pbr::OriginalName("ADD")] Add = 0, + [pbr::OriginalName("REMOVE")] Remove = 1, + } + + } + #endregion + + } + + public sealed partial class StartPitayaRequest : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new StartPitayaRequest()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[2]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public StartPitayaRequest() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public StartPitayaRequest(StartPitayaRequest other) : this() { + config_ = other.config_ != null ? other.config_.Clone() : null; + shouldCompressMessages_ = other.shouldCompressMessages_; + debugLog_ = other.debugLog_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public StartPitayaRequest Clone() { + return new StartPitayaRequest(this); + } + + /// Field number for the "config" field. + public const int ConfigFieldNumber = 1; + private global::NPitaya.Protos.Server config_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Server Config { + get { return config_; } + set { + config_ = value; + } + } + + /// Field number for the "shouldCompressMessages" field. + public const int ShouldCompressMessagesFieldNumber = 2; + private bool shouldCompressMessages_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool ShouldCompressMessages { + get { return shouldCompressMessages_; } + set { + shouldCompressMessages_ = value; + } + } + + /// Field number for the "debugLog" field. + public const int DebugLogFieldNumber = 3; + private bool debugLog_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool DebugLog { + get { return debugLog_; } + set { + debugLog_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as StartPitayaRequest); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(StartPitayaRequest other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(Config, other.Config)) return false; + if (ShouldCompressMessages != other.ShouldCompressMessages) return false; + if (DebugLog != other.DebugLog) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (config_ != null) hash ^= Config.GetHashCode(); + if (ShouldCompressMessages != false) hash ^= ShouldCompressMessages.GetHashCode(); + if (DebugLog != false) hash ^= DebugLog.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (config_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Config); + } + if (ShouldCompressMessages != false) { + output.WriteRawTag(16); + output.WriteBool(ShouldCompressMessages); + } + if (DebugLog != false) { + output.WriteRawTag(24); + output.WriteBool(DebugLog); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (config_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Config); + } + if (ShouldCompressMessages != false) { + output.WriteRawTag(16); + output.WriteBool(ShouldCompressMessages); + } + if (DebugLog != false) { + output.WriteRawTag(24); + output.WriteBool(DebugLog); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (config_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Config); + } + if (ShouldCompressMessages != false) { + size += 1 + 1; + } + if (DebugLog != false) { + size += 1 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(StartPitayaRequest other) { + if (other == null) { + return; + } + if (other.config_ != null) { + if (config_ == null) { + Config = new global::NPitaya.Protos.Server(); + } + Config.MergeFrom(other.Config); + } + if (other.ShouldCompressMessages != false) { + ShouldCompressMessages = other.ShouldCompressMessages; + } + if (other.DebugLog != false) { + DebugLog = other.DebugLog; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (config_ == null) { + Config = new global::NPitaya.Protos.Server(); + } + input.ReadMessage(Config); + break; + } + case 16: { + ShouldCompressMessages = input.ReadBool(); + break; + } + case 24: { + DebugLog = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (config_ == null) { + Config = new global::NPitaya.Protos.Server(); + } + input.ReadMessage(Config); + break; + } + case 16: { + ShouldCompressMessages = input.ReadBool(); + break; + } + case 24: { + DebugLog = input.ReadBool(); + break; + } + } + } + } + #endif + + } + + public sealed partial class RequestTo : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new RequestTo()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[3]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RequestTo() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RequestTo(RequestTo other) : this() { + serverID_ = other.serverID_; + msg_ = other.msg_ != null ? other.msg_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RequestTo Clone() { + return new RequestTo(this); + } + + /// Field number for the "serverID" field. + public const int ServerIDFieldNumber = 1; + private string serverID_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string ServerID { + get { return serverID_; } + set { + serverID_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "msg" field. + public const int MsgFieldNumber = 2; + private global::NPitaya.Protos.Msg msg_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Msg Msg { + get { return msg_; } + set { + msg_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as RequestTo); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(RequestTo other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (ServerID != other.ServerID) return false; + if (!object.Equals(Msg, other.Msg)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (ServerID.Length != 0) hash ^= ServerID.GetHashCode(); + if (msg_ != null) hash ^= Msg.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (ServerID.Length != 0) { + output.WriteRawTag(10); + output.WriteString(ServerID); + } + if (msg_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Msg); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (ServerID.Length != 0) { + output.WriteRawTag(10); + output.WriteString(ServerID); + } + if (msg_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Msg); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (ServerID.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(ServerID); + } + if (msg_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Msg); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(RequestTo other) { + if (other == null) { + return; + } + if (other.ServerID.Length != 0) { + ServerID = other.ServerID; + } + if (other.msg_ != null) { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + Msg.MergeFrom(other.Msg); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + ServerID = input.ReadString(); + break; + } + case 18: { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + input.ReadMessage(Msg); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + ServerID = input.ReadString(); + break; + } + case 18: { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + input.ReadMessage(Msg); + break; + } + } + } + } + #endif + + } + + public sealed partial class RPCResponse : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new RPCResponse()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[4]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCResponse() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCResponse(RPCResponse other) : this() { + reqId_ = other.reqId_; + res_ = other.res_ != null ? other.res_.Clone() : null; + err_ = other.err_ != null ? other.err_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCResponse Clone() { + return new RPCResponse(this); + } + + /// Field number for the "reqId" field. + public const int ReqIdFieldNumber = 1; + private ulong reqId_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ulong ReqId { + get { return reqId_; } + set { + reqId_ = value; + } + } + + /// Field number for the "res" field. + public const int ResFieldNumber = 2; + private global::NPitaya.Protos.Response res_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Response Res { + get { return res_; } + set { + res_ = value; + } + } + + /// Field number for the "err" field. + public const int ErrFieldNumber = 3; + private global::NPitaya.Protos.Error err_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Error Err { + get { return err_; } + set { + err_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as RPCResponse); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(RPCResponse other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (ReqId != other.ReqId) return false; + if (!object.Equals(Res, other.Res)) return false; + if (!object.Equals(Err, other.Err)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (ReqId != 0UL) hash ^= ReqId.GetHashCode(); + if (res_ != null) hash ^= Res.GetHashCode(); + if (err_ != null) hash ^= Err.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (ReqId != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(ReqId); + } + if (res_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Res); + } + if (err_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Err); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (ReqId != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(ReqId); + } + if (res_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Res); + } + if (err_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Err); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (ReqId != 0UL) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(ReqId); + } + if (res_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Res); + } + if (err_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Err); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(RPCResponse other) { + if (other == null) { + return; + } + if (other.ReqId != 0UL) { + ReqId = other.ReqId; + } + if (other.res_ != null) { + if (res_ == null) { + Res = new global::NPitaya.Protos.Response(); + } + Res.MergeFrom(other.Res); + } + if (other.err_ != null) { + if (err_ == null) { + Err = new global::NPitaya.Protos.Error(); + } + Err.MergeFrom(other.Err); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + ReqId = input.ReadUInt64(); + break; + } + case 18: { + if (res_ == null) { + Res = new global::NPitaya.Protos.Response(); + } + input.ReadMessage(Res); + break; + } + case 26: { + if (err_ == null) { + Err = new global::NPitaya.Protos.Error(); + } + input.ReadMessage(Err); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + ReqId = input.ReadUInt64(); + break; + } + case 18: { + if (res_ == null) { + Res = new global::NPitaya.Protos.Response(); + } + input.ReadMessage(Res); + break; + } + case 26: { + if (err_ == null) { + Err = new global::NPitaya.Protos.Error(); + } + input.ReadMessage(Err); + break; + } + } + } + } + #endif + + } + + public sealed partial class SidecarRequest : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SidecarRequest()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[5]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SidecarRequest() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SidecarRequest(SidecarRequest other) : this() { + reqId_ = other.reqId_; + req_ = other.req_ != null ? other.req_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SidecarRequest Clone() { + return new SidecarRequest(this); + } + + /// Field number for the "reqId" field. + public const int ReqIdFieldNumber = 1; + private ulong reqId_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ulong ReqId { + get { return reqId_; } + set { + reqId_ = value; + } + } + + /// Field number for the "req" field. + public const int ReqFieldNumber = 2; + private global::NPitaya.Protos.Request req_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Request Req { + get { return req_; } + set { + req_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as SidecarRequest); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(SidecarRequest other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (ReqId != other.ReqId) return false; + if (!object.Equals(Req, other.Req)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (ReqId != 0UL) hash ^= ReqId.GetHashCode(); + if (req_ != null) hash ^= Req.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (ReqId != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(ReqId); + } + if (req_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Req); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (ReqId != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(ReqId); + } + if (req_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Req); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (ReqId != 0UL) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(ReqId); + } + if (req_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Req); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(SidecarRequest other) { + if (other == null) { + return; + } + if (other.ReqId != 0UL) { + ReqId = other.ReqId; + } + if (other.req_ != null) { + if (req_ == null) { + Req = new global::NPitaya.Protos.Request(); + } + Req.MergeFrom(other.Req); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + ReqId = input.ReadUInt64(); + break; + } + case 18: { + if (req_ == null) { + Req = new global::NPitaya.Protos.Request(); + } + input.ReadMessage(Req); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + ReqId = input.ReadUInt64(); + break; + } + case 18: { + if (req_ == null) { + Req = new global::NPitaya.Protos.Request(); + } + input.ReadMessage(Req); + break; + } + } + } + } + #endif + + } + + public sealed partial class PushRequest : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new PushRequest()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[6]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushRequest() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushRequest(PushRequest other) : this() { + frontendType_ = other.frontendType_; + push_ = other.push_ != null ? other.push_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushRequest Clone() { + return new PushRequest(this); + } + + /// Field number for the "frontendType" field. + public const int FrontendTypeFieldNumber = 2; + private string frontendType_ = ""; + /// + /// TODO I think this field is not needed if we use nats only + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string FrontendType { + get { return frontendType_; } + set { + frontendType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "push" field. + public const int PushFieldNumber = 3; + private global::NPitaya.Protos.Push push_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Push Push { + get { return push_; } + set { + push_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as PushRequest); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(PushRequest other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (FrontendType != other.FrontendType) return false; + if (!object.Equals(Push, other.Push)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (FrontendType.Length != 0) hash ^= FrontendType.GetHashCode(); + if (push_ != null) hash ^= Push.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (FrontendType.Length != 0) { + output.WriteRawTag(18); + output.WriteString(FrontendType); + } + if (push_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Push); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (FrontendType.Length != 0) { + output.WriteRawTag(18); + output.WriteString(FrontendType); + } + if (push_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Push); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (FrontendType.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FrontendType); + } + if (push_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Push); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(PushRequest other) { + if (other == null) { + return; + } + if (other.FrontendType.Length != 0) { + FrontendType = other.FrontendType; + } + if (other.push_ != null) { + if (push_ == null) { + Push = new global::NPitaya.Protos.Push(); + } + Push.MergeFrom(other.Push); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 18: { + FrontendType = input.ReadString(); + break; + } + case 26: { + if (push_ == null) { + Push = new global::NPitaya.Protos.Push(); + } + input.ReadMessage(Push); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 18: { + FrontendType = input.ReadString(); + break; + } + case 26: { + if (push_ == null) { + Push = new global::NPitaya.Protos.Push(); + } + input.ReadMessage(Push); + break; + } + } + } + } + #endif + + } + + public sealed partial class PushResponse : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new PushResponse()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[7]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushResponse() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushResponse(PushResponse other) : this() { + failedUids_ = other.failedUids_.Clone(); + hasFailed_ = other.hasFailed_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushResponse Clone() { + return new PushResponse(this); + } + + /// Field number for the "failedUids" field. + public const int FailedUidsFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_failedUids_codec + = pb::FieldCodec.ForString(10); + private readonly pbc::RepeatedField failedUids_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::RepeatedField FailedUids { + get { return failedUids_; } + } + + /// Field number for the "hasFailed" field. + public const int HasFailedFieldNumber = 2; + private bool hasFailed_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool HasFailed { + get { return hasFailed_; } + set { + hasFailed_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as PushResponse); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(PushResponse other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!failedUids_.Equals(other.failedUids_)) return false; + if (HasFailed != other.HasFailed) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + hash ^= failedUids_.GetHashCode(); + if (HasFailed != false) hash ^= HasFailed.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + failedUids_.WriteTo(output, _repeated_failedUids_codec); + if (HasFailed != false) { + output.WriteRawTag(16); + output.WriteBool(HasFailed); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + failedUids_.WriteTo(ref output, _repeated_failedUids_codec); + if (HasFailed != false) { + output.WriteRawTag(16); + output.WriteBool(HasFailed); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + size += failedUids_.CalculateSize(_repeated_failedUids_codec); + if (HasFailed != false) { + size += 1 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(PushResponse other) { + if (other == null) { + return; + } + failedUids_.Add(other.failedUids_); + if (other.HasFailed != false) { + HasFailed = other.HasFailed; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + failedUids_.AddEntriesFrom(input, _repeated_failedUids_codec); + break; + } + case 16: { + HasFailed = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + failedUids_.AddEntriesFrom(ref input, _repeated_failedUids_codec); + break; + } + case 16: { + HasFailed = input.ReadBool(); + break; + } + } + } + } + #endif + + } + + public sealed partial class KickRequest : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new KickRequest()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[8]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickRequest() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickRequest(KickRequest other) : this() { + frontendType_ = other.frontendType_; + kick_ = other.kick_ != null ? other.kick_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickRequest Clone() { + return new KickRequest(this); + } + + /// Field number for the "frontendType" field. + public const int FrontendTypeFieldNumber = 2; + private string frontendType_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string FrontendType { + get { return frontendType_; } + set { + frontendType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "kick" field. + public const int KickFieldNumber = 3; + private global::NPitaya.Protos.KickMsg kick_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.KickMsg Kick { + get { return kick_; } + set { + kick_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as KickRequest); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(KickRequest other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (FrontendType != other.FrontendType) return false; + if (!object.Equals(Kick, other.Kick)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (FrontendType.Length != 0) hash ^= FrontendType.GetHashCode(); + if (kick_ != null) hash ^= Kick.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (FrontendType.Length != 0) { + output.WriteRawTag(18); + output.WriteString(FrontendType); + } + if (kick_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Kick); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (FrontendType.Length != 0) { + output.WriteRawTag(18); + output.WriteString(FrontendType); + } + if (kick_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Kick); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (FrontendType.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FrontendType); + } + if (kick_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Kick); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(KickRequest other) { + if (other == null) { + return; + } + if (other.FrontendType.Length != 0) { + FrontendType = other.FrontendType; + } + if (other.kick_ != null) { + if (kick_ == null) { + Kick = new global::NPitaya.Protos.KickMsg(); + } + Kick.MergeFrom(other.Kick); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 18: { + FrontendType = input.ReadString(); + break; + } + case 26: { + if (kick_ == null) { + Kick = new global::NPitaya.Protos.KickMsg(); + } + input.ReadMessage(Kick); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 18: { + FrontendType = input.ReadString(); + break; + } + case 26: { + if (kick_ == null) { + Kick = new global::NPitaya.Protos.KickMsg(); + } + input.ReadMessage(Kick); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/NPitaya/src/gen/SidecarGrpc.cs b/csharp/NPitaya/src/gen/SidecarGrpc.cs new file mode 100644 index 00000000..d316bdaf --- /dev/null +++ b/csharp/NPitaya/src/gen/SidecarGrpc.cs @@ -0,0 +1,405 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: sidecar.proto +// +#pragma warning disable 0414, 1591 +#region Designer generated code + +using grpc = global::Grpc.Core; + +namespace NPitaya.Protos { + public static partial class Sidecar + { + static readonly string __ServiceName = "protos.Sidecar"; + + static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context) + { + #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION + if (message is global::Google.Protobuf.IBufferMessage) + { + context.SetPayloadLength(message.CalculateSize()); + global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter()); + context.Complete(); + return; + } + #endif + context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message)); + } + + static class __Helper_MessageCache + { + public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T)); + } + + static T __Helper_DeserializeMessage(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser parser) where T : global::Google.Protobuf.IMessage + { + #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION + if (__Helper_MessageCache.IsBufferMessage) + { + return parser.ParseFrom(context.PayloadAsReadOnlySequence()); + } + #endif + return parser.ParseFrom(context.PayloadAsNewBuffer()); + } + + static readonly grpc::Marshaller __Marshaller_protos_Server = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Server.Parser)); + static readonly grpc::Marshaller __Marshaller_google_protobuf_Empty = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Protobuf.WellKnownTypes.Empty.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_RPCResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.RPCResponse.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_SidecarRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.SidecarRequest.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_SDEvent = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.SDEvent.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_RequestTo = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.RequestTo.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_Response = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Response.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_PushRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.PushRequest.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_PushResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.PushResponse.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_KickRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.KickRequest.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_StartPitayaRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.StartPitayaRequest.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_Error = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Error.Parser)); + + static readonly grpc::Method __Method_GetServer = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "GetServer", + __Marshaller_protos_Server, + __Marshaller_protos_Server); + + static readonly grpc::Method __Method_Heartbeat = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "Heartbeat", + __Marshaller_google_protobuf_Empty, + __Marshaller_google_protobuf_Empty); + + static readonly grpc::Method __Method_ListenRPC = new grpc::Method( + grpc::MethodType.DuplexStreaming, + __ServiceName, + "ListenRPC", + __Marshaller_protos_RPCResponse, + __Marshaller_protos_SidecarRequest); + + static readonly grpc::Method __Method_ListenSD = new grpc::Method( + grpc::MethodType.ServerStreaming, + __ServiceName, + "ListenSD", + __Marshaller_google_protobuf_Empty, + __Marshaller_protos_SDEvent); + + static readonly grpc::Method __Method_SendRPC = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "SendRPC", + __Marshaller_protos_RequestTo, + __Marshaller_protos_Response); + + static readonly grpc::Method __Method_SendPush = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "SendPush", + __Marshaller_protos_PushRequest, + __Marshaller_protos_PushResponse); + + static readonly grpc::Method __Method_SendKick = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "SendKick", + __Marshaller_protos_KickRequest, + __Marshaller_protos_PushResponse); + + static readonly grpc::Method __Method_StartPitaya = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "StartPitaya", + __Marshaller_protos_StartPitayaRequest, + __Marshaller_protos_Error); + + static readonly grpc::Method __Method_StopPitaya = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "StopPitaya", + __Marshaller_google_protobuf_Empty, + __Marshaller_protos_Error); + + /// Service descriptor + public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor + { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.Services[0]; } + } + + /// Base class for server-side implementations of Sidecar + [grpc::BindServiceMethod(typeof(Sidecar), "BindService")] + public abstract partial class SidecarBase + { + public virtual global::System.Threading.Tasks.Task GetServer(global::NPitaya.Protos.Server request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task Heartbeat(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task ListenRPC(grpc::IAsyncStreamReader requestStream, grpc::IServerStreamWriter responseStream, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task ListenSD(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::IServerStreamWriter responseStream, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task SendRPC(global::NPitaya.Protos.RequestTo request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task SendPush(global::NPitaya.Protos.PushRequest request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task SendKick(global::NPitaya.Protos.KickRequest request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task StartPitaya(global::NPitaya.Protos.StartPitayaRequest request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + /// + /// AddRoute + /// + /// The request received from the client. + /// The context of the server-side call handler being invoked. + /// The response to send back to the client (wrapped by a task). + public virtual global::System.Threading.Tasks.Task StopPitaya(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + } + + /// Client for Sidecar + public partial class SidecarClient : grpc::ClientBase + { + /// Creates a new client for Sidecar + /// The channel to use to make remote calls. + public SidecarClient(grpc::ChannelBase channel) : base(channel) + { + } + /// Creates a new client for Sidecar that uses a custom CallInvoker. + /// The callInvoker to use to make remote calls. + public SidecarClient(grpc::CallInvoker callInvoker) : base(callInvoker) + { + } + /// Protected parameterless constructor to allow creation of test doubles. + protected SidecarClient() : base() + { + } + /// Protected constructor to allow creation of configured clients. + /// The client configuration. + protected SidecarClient(ClientBaseConfiguration configuration) : base(configuration) + { + } + + public virtual global::NPitaya.Protos.Server GetServer(global::NPitaya.Protos.Server request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return GetServer(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Server GetServer(global::NPitaya.Protos.Server request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_GetServer, null, options, request); + } + public virtual grpc::AsyncUnaryCall GetServerAsync(global::NPitaya.Protos.Server request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return GetServerAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall GetServerAsync(global::NPitaya.Protos.Server request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_GetServer, null, options, request); + } + public virtual global::Google.Protobuf.WellKnownTypes.Empty Heartbeat(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return Heartbeat(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::Google.Protobuf.WellKnownTypes.Empty Heartbeat(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_Heartbeat, null, options, request); + } + public virtual grpc::AsyncUnaryCall HeartbeatAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return HeartbeatAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall HeartbeatAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_Heartbeat, null, options, request); + } + public virtual grpc::AsyncDuplexStreamingCall ListenRPC(grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return ListenRPC(new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncDuplexStreamingCall ListenRPC(grpc::CallOptions options) + { + return CallInvoker.AsyncDuplexStreamingCall(__Method_ListenRPC, null, options); + } + public virtual grpc::AsyncServerStreamingCall ListenSD(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return ListenSD(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncServerStreamingCall ListenSD(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) + { + return CallInvoker.AsyncServerStreamingCall(__Method_ListenSD, null, options, request); + } + public virtual global::NPitaya.Protos.Response SendRPC(global::NPitaya.Protos.RequestTo request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendRPC(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Response SendRPC(global::NPitaya.Protos.RequestTo request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_SendRPC, null, options, request); + } + public virtual grpc::AsyncUnaryCall SendRPCAsync(global::NPitaya.Protos.RequestTo request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendRPCAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall SendRPCAsync(global::NPitaya.Protos.RequestTo request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_SendRPC, null, options, request); + } + public virtual global::NPitaya.Protos.PushResponse SendPush(global::NPitaya.Protos.PushRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendPush(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.PushResponse SendPush(global::NPitaya.Protos.PushRequest request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_SendPush, null, options, request); + } + public virtual grpc::AsyncUnaryCall SendPushAsync(global::NPitaya.Protos.PushRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendPushAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall SendPushAsync(global::NPitaya.Protos.PushRequest request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_SendPush, null, options, request); + } + public virtual global::NPitaya.Protos.PushResponse SendKick(global::NPitaya.Protos.KickRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendKick(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.PushResponse SendKick(global::NPitaya.Protos.KickRequest request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_SendKick, null, options, request); + } + public virtual grpc::AsyncUnaryCall SendKickAsync(global::NPitaya.Protos.KickRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendKickAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall SendKickAsync(global::NPitaya.Protos.KickRequest request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_SendKick, null, options, request); + } + public virtual global::NPitaya.Protos.Error StartPitaya(global::NPitaya.Protos.StartPitayaRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return StartPitaya(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Error StartPitaya(global::NPitaya.Protos.StartPitayaRequest request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_StartPitaya, null, options, request); + } + public virtual grpc::AsyncUnaryCall StartPitayaAsync(global::NPitaya.Protos.StartPitayaRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return StartPitayaAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall StartPitayaAsync(global::NPitaya.Protos.StartPitayaRequest request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_StartPitaya, null, options, request); + } + /// + /// AddRoute + /// + /// The request to send to the server. + /// The initial metadata to send with the call. This parameter is optional. + /// An optional deadline for the call. The call will be cancelled if deadline is hit. + /// An optional token for canceling the call. + /// The response received from the server. + public virtual global::NPitaya.Protos.Error StopPitaya(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return StopPitaya(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + /// + /// AddRoute + /// + /// The request to send to the server. + /// The options for the call. + /// The response received from the server. + public virtual global::NPitaya.Protos.Error StopPitaya(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_StopPitaya, null, options, request); + } + /// + /// AddRoute + /// + /// The request to send to the server. + /// The initial metadata to send with the call. This parameter is optional. + /// An optional deadline for the call. The call will be cancelled if deadline is hit. + /// An optional token for canceling the call. + /// The call object. + public virtual grpc::AsyncUnaryCall StopPitayaAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return StopPitayaAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + /// + /// AddRoute + /// + /// The request to send to the server. + /// The options for the call. + /// The call object. + public virtual grpc::AsyncUnaryCall StopPitayaAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_StopPitaya, null, options, request); + } + /// Creates a new instance of client from given ClientBaseConfiguration. + protected override SidecarClient NewInstance(ClientBaseConfiguration configuration) + { + return new SidecarClient(configuration); + } + } + + /// Creates service definition that can be registered with a server + /// An object implementing the server-side handling logic. + public static grpc::ServerServiceDefinition BindService(SidecarBase serviceImpl) + { + return grpc::ServerServiceDefinition.CreateBuilder() + .AddMethod(__Method_GetServer, serviceImpl.GetServer) + .AddMethod(__Method_Heartbeat, serviceImpl.Heartbeat) + .AddMethod(__Method_ListenRPC, serviceImpl.ListenRPC) + .AddMethod(__Method_ListenSD, serviceImpl.ListenSD) + .AddMethod(__Method_SendRPC, serviceImpl.SendRPC) + .AddMethod(__Method_SendPush, serviceImpl.SendPush) + .AddMethod(__Method_SendKick, serviceImpl.SendKick) + .AddMethod(__Method_StartPitaya, serviceImpl.StartPitaya) + .AddMethod(__Method_StopPitaya, serviceImpl.StopPitaya).Build(); + } + + /// Register service method with a service binder with or without implementation. Useful when customizing the service binding logic. + /// Note: this method is part of an experimental API that can change or be removed without any prior notice. + /// Service methods will be bound by calling AddMethod on this object. + /// An object implementing the server-side handling logic. + public static void BindService(grpc::ServiceBinderBase serviceBinder, SidecarBase serviceImpl) + { + serviceBinder.AddMethod(__Method_GetServer, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.GetServer)); + serviceBinder.AddMethod(__Method_Heartbeat, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.Heartbeat)); + serviceBinder.AddMethod(__Method_ListenRPC, serviceImpl == null ? null : new grpc::DuplexStreamingServerMethod(serviceImpl.ListenRPC)); + serviceBinder.AddMethod(__Method_ListenSD, serviceImpl == null ? null : new grpc::ServerStreamingServerMethod(serviceImpl.ListenSD)); + serviceBinder.AddMethod(__Method_SendRPC, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.SendRPC)); + serviceBinder.AddMethod(__Method_SendPush, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.SendPush)); + serviceBinder.AddMethod(__Method_SendKick, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.SendKick)); + serviceBinder.AddMethod(__Method_StartPitaya, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.StartPitaya)); + serviceBinder.AddMethod(__Method_StopPitaya, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.StopPitaya)); + } + + } +} +#endregion diff --git a/csharp/docker-compose.yml b/csharp/docker-compose.yml new file mode 100644 index 00000000..b5a364cc --- /dev/null +++ b/csharp/docker-compose.yml @@ -0,0 +1,10 @@ +version: '3' +services: + nats: + image: nats + ports: + - 4222:4222 + etcd: + image: appcelerator/etcd + ports: + - 2379:2379 diff --git a/csharp/examples/ExampleEFCore/ExampleEFCore.csproj b/csharp/examples/ExampleEFCore/ExampleEFCore.csproj new file mode 100644 index 00000000..2d9a156e --- /dev/null +++ b/csharp/examples/ExampleEFCore/ExampleEFCore.csproj @@ -0,0 +1,48 @@ + + + + Exe + netcoreapp3.1 + example_orm + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/csharp/examples/ExampleEFCore/Migrations/20190328153447_InitialMigration.Designer.cs b/csharp/examples/ExampleEFCore/Migrations/20190328153447_InitialMigration.Designer.cs new file mode 100644 index 00000000..566158de --- /dev/null +++ b/csharp/examples/ExampleEFCore/Migrations/20190328153447_InitialMigration.Designer.cs @@ -0,0 +1,55 @@ +// +using System; +using ExampleORM.Models; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +namespace example_orm.Migrations +{ + [DbContext(typeof(ExampleContext))] + [Migration("20190328153447_InitialMigration")] + partial class InitialMigration + { + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Npgsql:PostgresExtension:uuid-ossp", ",,") + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn) + .HasAnnotation("ProductVersion", "2.2.3-servicing-35854") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + modelBuilder.Entity("ExampleORM.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnName("id"); + + b.Property("Name") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnName("name") + .HasDefaultValue("Player"); + + b.Property("Token") + .ValueGeneratedOnAdd() + .HasColumnName("token") + .HasDefaultValueSql("uuid_generate_v4()"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnName("updated_at") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.ToTable("users"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/csharp/examples/ExampleEFCore/Migrations/20190328153447_InitialMigration.cs b/csharp/examples/ExampleEFCore/Migrations/20190328153447_InitialMigration.cs new file mode 100644 index 00000000..9c3f6d05 --- /dev/null +++ b/csharp/examples/ExampleEFCore/Migrations/20190328153447_InitialMigration.cs @@ -0,0 +1,34 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace example_orm.Migrations +{ + public partial class InitialMigration : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AlterDatabase() + .Annotation("Npgsql:PostgresExtension:uuid-ossp", ",,"); + + migrationBuilder.CreateTable( + name: "users", + columns: table => new + { + id = table.Column(nullable: false), + name = table.Column(nullable: false, defaultValue: "Player"), + token = table.Column(nullable: false, defaultValueSql: "uuid_generate_v4()"), + updated_at = table.Column(nullable: false, defaultValueSql: "NOW()") + }, + constraints: table => + { + table.PrimaryKey("pk_users", x => x.id); + }); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "users"); + } + } +} diff --git a/csharp/examples/ExampleEFCore/Migrations/ExampleContextModelSnapshot.cs b/csharp/examples/ExampleEFCore/Migrations/ExampleContextModelSnapshot.cs new file mode 100644 index 00000000..b3766dde --- /dev/null +++ b/csharp/examples/ExampleEFCore/Migrations/ExampleContextModelSnapshot.cs @@ -0,0 +1,53 @@ +// +using System; +using ExampleORM.Models; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +namespace example_orm.Migrations +{ + [DbContext(typeof(ExampleContext))] + partial class ExampleContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Npgsql:PostgresExtension:uuid-ossp", ",,") + .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn) + .HasAnnotation("ProductVersion", "2.2.3-servicing-35854") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + modelBuilder.Entity("ExampleORM.Models.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnName("id"); + + b.Property("Name") + .IsRequired() + .ValueGeneratedOnAdd() + .HasColumnName("name") + .HasDefaultValue("Player"); + + b.Property("Token") + .ValueGeneratedOnAdd() + .HasColumnName("token") + .HasDefaultValueSql("uuid_generate_v4()"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAdd() + .HasColumnName("updated_at") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id") + .HasName("pk_users"); + + b.ToTable("users"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/csharp/examples/ExampleEFCore/Protos/Answer.proto b/csharp/examples/ExampleEFCore/Protos/Answer.proto new file mode 100644 index 00000000..7dc88967 --- /dev/null +++ b/csharp/examples/ExampleEFCore/Protos/Answer.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; + +package Gen.Protos; + +message Answer { + string code = 1; +} \ No newline at end of file diff --git a/csharp/examples/ExampleEFCore/Protos/AuthenticateArgs.proto b/csharp/examples/ExampleEFCore/Protos/AuthenticateArgs.proto new file mode 100644 index 00000000..dcbc4f6c --- /dev/null +++ b/csharp/examples/ExampleEFCore/Protos/AuthenticateArgs.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; + +package Gen.Protos; + +message AuthenticateArgs { + string token = 1; +} diff --git a/csharp/examples/ExampleEFCore/Protos/ChangeNameArg.proto b/csharp/examples/ExampleEFCore/Protos/ChangeNameArg.proto new file mode 100644 index 00000000..64aee595 --- /dev/null +++ b/csharp/examples/ExampleEFCore/Protos/ChangeNameArg.proto @@ -0,0 +1,8 @@ +syntax = "proto3"; + +package Gen.Protos; + +message ChangeNameArgs { + string token = 1; + string name = 2; +} \ No newline at end of file diff --git a/csharp/examples/ExampleEFCore/Protos/user.proto b/csharp/examples/ExampleEFCore/Protos/user.proto new file mode 100644 index 00000000..9b3b30bf --- /dev/null +++ b/csharp/examples/ExampleEFCore/Protos/user.proto @@ -0,0 +1,9 @@ +syntax = "proto3"; + +package Gen.Protos; + +message User { + string id = 1; + string name = 2; + string token = 3; +} diff --git a/csharp/examples/ExampleEFCore/src/App.cs b/csharp/examples/ExampleEFCore/src/App.cs new file mode 100644 index 00000000..6f2bf661 --- /dev/null +++ b/csharp/examples/ExampleEFCore/src/App.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using ExampleORM.Servers.BusinessLogic.Handlers; +using NPitaya; +using NPitaya.Models; +using NPitaya.Serializer; + +namespace ExampleORM +{ + class App + { + private static void Main(string[] args) + { + Logger.SetLevel(LogLevel.INFO); + + var serverId = System.Guid.NewGuid().ToString(); + + var sdConfig = new SDConfig( + endpoints: "http://127.0.0.1:2379", + etcdPrefix: "pitaya/", + serverTypeFilters: new List(), + heartbeatTTLSec: 60, + logHeartbeat: true, + logServerSync: true, + logServerDetails: true, + syncServersIntervalSec: 30, + maxNumberOfRetries: 0); + + var sv = new Server( + id: serverId, + type: "csharp", + metadata: "", + hostname: "localhost", + frontend: false); + + var grpcConfig = new GrpcConfig( + host: "127.0.0.1", + port: 5444, + serverShutdownDeadlineMs: 3000, + serverMaxNumberOfRpcs: 500, + clientRpcTimeoutMs: 10000 + ); + + PitayaCluster.AddSignalHandler(() => + { + Logger.Info("Calling terminate on cluster"); + PitayaCluster.Terminate(); + Logger.Info("Cluster terminated, exiting app"); + Environment.Exit(1); + }); + + PitayaCluster.SetSerializer(new JSONSerializer()); // Using json serializer for easier interop with pitaya-cli + + try + { + PitayaCluster.Initialize( + grpcConfig, + sdConfig, + sv, + NativeLogLevel.Debug, + new PitayaCluster.ServiceDiscoveryListener((action, server) => + { + switch (action) + { + case PitayaCluster.ServiceDiscoveryAction.ServerAdded: + Console.WriteLine($"Server added: {server}"); + break; + case PitayaCluster.ServiceDiscoveryAction.ServerRemoved: + Console.WriteLine($"Server removed: {server}"); + break; + default: + throw new ArgumentOutOfRangeException(nameof(action), action, null); + } + }) + ); + } + catch (PitayaException exc) + { + Logger.Error("Failed to create cluster: {0}", exc.Message); + Environment.Exit(1); + } + + while (true) + { + Thread.Sleep(10); + } + //// + } + } +} diff --git a/csharp/examples/ExampleEFCore/src/Extensions/StringExtensions.cs b/csharp/examples/ExampleEFCore/src/Extensions/StringExtensions.cs new file mode 100644 index 00000000..a311435e --- /dev/null +++ b/csharp/examples/ExampleEFCore/src/Extensions/StringExtensions.cs @@ -0,0 +1,18 @@ +using System.Text.RegularExpressions; + +namespace ExampleORM.Extensions +{ + public static class StringExtensions + { + public static string ToSnakeCase(this string input) + { + if (string.IsNullOrEmpty(input)) + { + return input; + } + + var startUnderscores = Regex.Match(input, @"^_+"); + return startUnderscores + Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1_$2").ToLower(); + } + } +} \ No newline at end of file diff --git a/csharp/examples/ExampleEFCore/src/Gen/Protos/Answer.cs b/csharp/examples/ExampleEFCore/src/Gen/Protos/Answer.cs new file mode 100644 index 00000000..1b40b065 --- /dev/null +++ b/csharp/examples/ExampleEFCore/src/Gen/Protos/Answer.cs @@ -0,0 +1,172 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: Protos/Answer.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Gen.Protos { + + /// Holder for reflection information generated from Protos/Answer.proto + public static partial class AnswerReflection { + + #region Descriptor + /// File descriptor for Protos/Answer.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static AnswerReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChNQcm90b3MvQW5zd2VyLnByb3RvEgpHZW4uUHJvdG9zIhYKBkFuc3dlchIM", + "CgRjb2RlGAEgASgJYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Gen.Protos.Answer), global::Gen.Protos.Answer.Parser, new[]{ "Code" }, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Answer : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Answer()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Gen.Protos.AnswerReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Answer() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Answer(Answer other) : this() { + code_ = other.code_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Answer Clone() { + return new Answer(this); + } + + /// Field number for the "code" field. + public const int CodeFieldNumber = 1; + private string code_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Code { + get { return code_; } + set { + code_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Answer); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Answer other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Code != other.Code) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Code.Length != 0) hash ^= Code.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (Code.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Code); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Code.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Code); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Answer other) { + if (other == null) { + return; + } + if (other.Code.Length != 0) { + Code = other.Code; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Code = input.ReadString(); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/ExampleEFCore/src/Gen/Protos/AuthenticateArgs.cs b/csharp/examples/ExampleEFCore/src/Gen/Protos/AuthenticateArgs.cs new file mode 100644 index 00000000..4aafa4d9 --- /dev/null +++ b/csharp/examples/ExampleEFCore/src/Gen/Protos/AuthenticateArgs.cs @@ -0,0 +1,172 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: Protos/AuthenticateArgs.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Gen.Protos { + + /// Holder for reflection information generated from Protos/AuthenticateArgs.proto + public static partial class AuthenticateArgsReflection { + + #region Descriptor + /// File descriptor for Protos/AuthenticateArgs.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static AuthenticateArgsReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Ch1Qcm90b3MvQXV0aGVudGljYXRlQXJncy5wcm90bxIKR2VuLlByb3RvcyIh", + "ChBBdXRoZW50aWNhdGVBcmdzEg0KBXRva2VuGAEgASgJYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Gen.Protos.AuthenticateArgs), global::Gen.Protos.AuthenticateArgs.Parser, new[]{ "Token" }, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class AuthenticateArgs : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new AuthenticateArgs()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Gen.Protos.AuthenticateArgsReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public AuthenticateArgs() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public AuthenticateArgs(AuthenticateArgs other) : this() { + token_ = other.token_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public AuthenticateArgs Clone() { + return new AuthenticateArgs(this); + } + + /// Field number for the "token" field. + public const int TokenFieldNumber = 1; + private string token_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Token { + get { return token_; } + set { + token_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as AuthenticateArgs); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(AuthenticateArgs other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Token != other.Token) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Token.Length != 0) hash ^= Token.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (Token.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Token); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Token.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Token); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(AuthenticateArgs other) { + if (other == null) { + return; + } + if (other.Token.Length != 0) { + Token = other.Token; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Token = input.ReadString(); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/ExampleEFCore/src/Gen/Protos/ChangeNameArg.cs b/csharp/examples/ExampleEFCore/src/Gen/Protos/ChangeNameArg.cs new file mode 100644 index 00000000..c0fde742 --- /dev/null +++ b/csharp/examples/ExampleEFCore/src/Gen/Protos/ChangeNameArg.cs @@ -0,0 +1,201 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: Protos/ChangeNameArg.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Gen.Protos { + + /// Holder for reflection information generated from Protos/ChangeNameArg.proto + public static partial class ChangeNameArgReflection { + + #region Descriptor + /// File descriptor for Protos/ChangeNameArg.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static ChangeNameArgReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChpQcm90b3MvQ2hhbmdlTmFtZUFyZy5wcm90bxIKR2VuLlByb3RvcyItCg5D", + "aGFuZ2VOYW1lQXJncxINCgV0b2tlbhgBIAEoCRIMCgRuYW1lGAIgASgJYgZw", + "cm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Gen.Protos.ChangeNameArgs), global::Gen.Protos.ChangeNameArgs.Parser, new[]{ "Token", "Name" }, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class ChangeNameArgs : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ChangeNameArgs()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Gen.Protos.ChangeNameArgReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ChangeNameArgs() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ChangeNameArgs(ChangeNameArgs other) : this() { + token_ = other.token_; + name_ = other.name_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ChangeNameArgs Clone() { + return new ChangeNameArgs(this); + } + + /// Field number for the "token" field. + public const int TokenFieldNumber = 1; + private string token_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Token { + get { return token_; } + set { + token_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 2; + private string name_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Name { + get { return name_; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as ChangeNameArgs); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(ChangeNameArgs other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Token != other.Token) return false; + if (Name != other.Name) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Token.Length != 0) hash ^= Token.GetHashCode(); + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (Token.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Token); + } + if (Name.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Name); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Token.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Token); + } + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(ChangeNameArgs other) { + if (other == null) { + return; + } + if (other.Token.Length != 0) { + Token = other.Token; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Token = input.ReadString(); + break; + } + case 18: { + Name = input.ReadString(); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/ExampleEFCore/src/Gen/Protos/User.cs b/csharp/examples/ExampleEFCore/src/Gen/Protos/User.cs new file mode 100644 index 00000000..efeb99cf --- /dev/null +++ b/csharp/examples/ExampleEFCore/src/Gen/Protos/User.cs @@ -0,0 +1,228 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: Protos/user.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Gen.Protos { + + /// Holder for reflection information generated from Protos/user.proto + public static partial class UserReflection { + + #region Descriptor + /// File descriptor for Protos/user.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static UserReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChFQcm90b3MvdXNlci5wcm90bxIKR2VuLlByb3RvcyIvCgRVc2VyEgoKAmlk", + "GAEgASgJEgwKBG5hbWUYAiABKAkSDQoFdG9rZW4YAyABKAliBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Gen.Protos.User), global::Gen.Protos.User.Parser, new[]{ "Id", "Name", "Token" }, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class User : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new User()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Gen.Protos.UserReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public User() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public User(User other) : this() { + id_ = other.id_; + name_ = other.name_; + token_ = other.token_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public User Clone() { + return new User(this); + } + + /// Field number for the "id" field. + public const int IdFieldNumber = 1; + private string id_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Id { + get { return id_; } + set { + id_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 2; + private string name_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Name { + get { return name_; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "token" field. + public const int TokenFieldNumber = 3; + private string token_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Token { + get { return token_; } + set { + token_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as User); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(User other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Id != other.Id) return false; + if (Name != other.Name) return false; + if (Token != other.Token) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Id.Length != 0) hash ^= Id.GetHashCode(); + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (Token.Length != 0) hash ^= Token.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + if (Id.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Id); + } + if (Name.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Name); + } + if (Token.Length != 0) { + output.WriteRawTag(26); + output.WriteString(Token); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Id.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Id); + } + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (Token.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Token); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(User other) { + if (other == null) { + return; + } + if (other.Id.Length != 0) { + Id = other.Id; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + if (other.Token.Length != 0) { + Token = other.Token; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Id = input.ReadString(); + break; + } + case 18: { + Name = input.ReadString(); + break; + } + case 26: { + Token = input.ReadString(); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/ExampleEFCore/src/Models/Models.cs b/csharp/examples/ExampleEFCore/src/Models/Models.cs new file mode 100644 index 00000000..e14e98f8 --- /dev/null +++ b/csharp/examples/ExampleEFCore/src/Models/Models.cs @@ -0,0 +1,94 @@ +using System; +using System.Linq; +using ExampleORM.Extensions; +using Microsoft.EntityFrameworkCore; + +namespace ExampleORM.Models +{ + public interface IUpdateable + { + DateTime UpdatedAt { get; set; } + } + + public class ExampleContext : DbContext + { + public DbSet Users { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseNpgsql("Host=localhost;Port=9000;Username=pguser;Password=;Database=testdb"); + } + + private void EnsureCamelCase(ModelBuilder builder) + { + foreach (var entity in builder.Model.GetEntityTypes()) + { + // Replace table names + entity.Relational().TableName = entity.Relational().TableName.ToSnakeCase(); + + // Replace column names + foreach (var property in entity.GetProperties()) + { + property.Relational().ColumnName = property.Name.ToSnakeCase(); + } + + foreach (var key in entity.GetKeys()) + { + key.Relational().Name = key.Relational().Name.ToSnakeCase(); + } + + foreach (var key in entity.GetForeignKeys()) + { + key.Relational().Name = key.Relational().Name.ToSnakeCase(); + } + + foreach (var index in entity.GetIndexes()) + { + index.Relational().Name = index.Relational().Name.ToSnakeCase(); + } + } + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + EnsureCamelCase(modelBuilder); + var b = modelBuilder.Entity(); + b.Property(u => u.Name).IsRequired().HasDefaultValue("Player"); + b.Property(u => u.UpdatedAt).HasDefaultValueSql("NOW()"); + b.Property(u => u.Id); + b.HasKey(u => u.Id); + modelBuilder.HasPostgresExtension("uuid-ossp") + .Entity() + .Property(u => u.Token) + .HasDefaultValueSql("uuid_generate_v4()"); + } + + public override int SaveChanges() + { + var currentDateTime = DateTime.Now; + var entries = ChangeTracker.Entries().ToList(); + + var updatedEntries = entries.Where(e => e.Entity is IUpdateable) + .Where(e => e.State == EntityState.Modified) + .ToList(); + + updatedEntries.ForEach(e => + { + ((IUpdateable) e.Entity).UpdatedAt = currentDateTime; + Console.WriteLine(((IUpdateable) e.Entity).UpdatedAt); + }); + + return base.SaveChanges(); + } + } + + public class User : IUpdateable + { + public Guid Id { get; set; } + public string Name { get; set; } + public Guid Token { get; set; } + public DateTime UpdatedAt { get; set; } + } +} \ No newline at end of file diff --git a/csharp/examples/ExampleEFCore/src/Servers/BusinessLogic/Handlers/UserHandler.cs b/csharp/examples/ExampleEFCore/src/Servers/BusinessLogic/Handlers/UserHandler.cs new file mode 100644 index 00000000..4ee89916 --- /dev/null +++ b/csharp/examples/ExampleEFCore/src/Servers/BusinessLogic/Handlers/UserHandler.cs @@ -0,0 +1,60 @@ +using System; +using System.Threading.Tasks; +using ExampleORM.Models; +using Gen.Protos; +using Microsoft.EntityFrameworkCore; +using NPitaya.Models; +using User = Gen.Protos.User; + +namespace ExampleORM.Servers.BusinessLogic.Handlers +{ + public class UserHandler : BaseHandler + { + private async Task GetUserFromToken(Guid token, ExampleContext ctx) + { + return await ctx.Users.SingleAsync(u => u.Token == token); + } + + private User ModelsUserToProtosUser(Models.User modelsUser) + { + return new User + { + Id = modelsUser.Id.ToString(), + Name = modelsUser.Name, + Token = modelsUser.Token.ToString() + }; + } + + public async Task Authenticate(PitayaSession session, AuthenticateArgs args) + { + using (var context = new ExampleContext()) + { + if (args.Token.Length > 0) + { + return ModelsUserToProtosUser(await GetUserFromToken(new Guid(args.Token), context)); + } + + // if token was not sent, create an user and return! + var newUser = new Models.User(); + newUser = context.Users.Add(newUser).Entity; + await context.SaveChangesAsync(); + return ModelsUserToProtosUser(newUser); + } + } + + public async Task ChangeName(PitayaSession session, ChangeNameArgs arg) + { + using (var context = new ExampleContext()) + { + var userModel = await GetUserFromToken(new Guid(arg.Token), context); + userModel.Name = arg.Name; + context.Update(userModel); + await context.SaveChangesAsync(); + return new Answer + { + Code = "OK!" + }; + } + } + } +} \ No newline at end of file diff --git a/csharp/examples/sidecar/Handlers/TestHandler.cs b/csharp/examples/sidecar/Handlers/TestHandler.cs new file mode 100644 index 00000000..a85a74ce --- /dev/null +++ b/csharp/examples/sidecar/Handlers/TestHandler.cs @@ -0,0 +1,85 @@ +using System; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; +using NPitaya.Models; +using NPitaya.Protos; +using NPitaya; + +#pragma warning disable 1998 +namespace exampleapp.Handlers +{ + class TestHandler : BaseHandler + { + public async Task Entry(PitayaSession pitayaSession, Protos.RPCMsg msg) + { + Logger.Debug($"Received this msg {msg.Msg}"); + var response = new Protos.RPCRes + { + Msg = $"hello from csharp handler!!! :) {Guid.NewGuid().ToString()}", + Code = 200 + }; + return response; + } + + public async Task GetServer(PitayaSession session, Protos.RPCMsg msg) + { + return PitayaCluster.GetServerById(msg.Msg); + } + + public async Task NotifyBind(PitayaSession pitayaSession, Protos.RPCMsg msg) + { + var response = new Protos.RPCRes + { + Msg = $"hello from csharp handler!!! :) {Guid.NewGuid().ToString()}", + Code = 200 + }; + + await pitayaSession.Bind("uidbla"); + + Console.WriteLine("handler executed with arg {0}", msg); + Console.WriteLine("handler executed with session ipversion {0}", pitayaSession.GetString("ipversion")); + } + public async Task SetSessionDataTest(PitayaSession pitayaSession, Protos.RPCMsg msg) + { + pitayaSession.Set("msg", "testingMsg"); + pitayaSession.Set("int", 3); + pitayaSession.Set("double", 3.33); + await pitayaSession.PushToFrontend(); + } + + public async Task TestPush(PitayaSession pitayaSession) + { + Console.WriteLine("got empty notify"); + var msg = Encoding.UTF8.GetBytes("test felipe"); + var res = await pitayaSession.Push(new Protos.RPCRes{Code = 200, Msg = "this is a test push"}, "connector", "test.route"); + if (res.HasFailed) + { + Logger.Error("push to user failed! {0}", res.FailedUids); + } + } + + public async Task TestKick(PitayaSession pitayaSession) + { + var res = await pitayaSession.Kick("connector"); + if (res.HasFailed) + { + Logger.Error("kick user failed! {0}", res.FailedUids); + } + } + + [DataContract] + public class TestClass + { + [DataMember(Name = "msg")] + public string Msg; + [DataMember(Name = "code")] + public int Code; + } + + public async Task OnlyValidWithJson(PitayaSession s, TestClass t) + { + return t; + } + } +} diff --git a/csharp/examples/sidecar/Program.cs b/csharp/examples/sidecar/Program.cs new file mode 100644 index 00000000..54d1915d --- /dev/null +++ b/csharp/examples/sidecar/Program.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using NPitaya; +using NPitaya.Metrics; +using NPitaya.Models; +using NPitaya.Protos; + +namespace PitayaCSharpExample +{ + class Example + { + static void Main(string[] args) + { + Logger.SetLevel(LogLevel.DEBUG); + + Logger.Info("Starting Pitaya C#"); + + string serverId = System.Guid.NewGuid().ToString(); + + var metadata = new Dictionary(){ + {"testKey", "testValue"} + }; + + var sv = new NPitaya.Protos.Server{ + Id = serverId, + Type = "csharp", + Hostname = "localhost", + Frontend = false }; + sv.Metadata.Add(metadata); + + Dictionary constantTags = new Dictionary + { + {"game", "game"}, + {"serverType", "svType"} + }; + var statsdMR = new StatsdMetricsReporter("localhost", 5000, "game", constantTags); + MetricsReporters.AddMetricReporter(statsdMR); + var prometheusMR = new PrometheusMetricsReporter("default", "game", 9090); + MetricsReporters.AddMetricReporter(prometheusMR); + + PitayaCluster.AddSignalHandler(() => + { + Logger.Info("Signal received, exiting app"); + Environment.Exit(1); + //Environment.FailFast("oops"); + }); + + try + { + PitayaCluster.SetSerializer(new NPitaya.Serializer.JSONSerializer()); + var sockAddr = "unix://" + System.IO.Path.Combine(System.IO.Path.GetTempPath(), "pitaya.sock"); + Logger.Info("Connecting to pitaya sidecar at addr: {0}", sockAddr); + PitayaCluster.StartJaeger(sv, "pitaya-csharp-example", 1.0f); + PitayaCluster.Initialize( + sockAddr, + sv, + OnServiceDiscoveryEvent, + debug: true + ); + } + catch (PitayaException exc) + { + Logger.Error("Failed to create cluster: {0}", exc.Message); + Environment.Exit(1); + } + + Logger.Info("Pitaya C# initialized!"); + + Thread.Sleep(1000); + + //TrySendRpc(); + Console.ReadKey(); + //PitayaCluster.Terminate(); + } + + static void OnServiceDiscoveryEvent(SDEvent sdEvent){ + switch (sdEvent.Event) + { + case NPitaya.Protos.SDEvent.Types.Event.Add: + Logger.Info($"Server Added - Id: {sdEvent.Server.Id} Type: {sdEvent.Server.Type}"); + break; + case NPitaya.Protos.SDEvent.Types.Event.Remove: + Logger.Info($"Server Removed - Id: {sdEvent.Server.Id} Type: {sdEvent.Server.Type}"); + break; + default: + throw new ArgumentOutOfRangeException(nameof(sdEvent.Event), sdEvent.Event, null); + } + } + + static async void TrySendRpc(){ + try + { + var res = await PitayaCluster.Rpc(Route.FromString("csharp.testRemote.remote"), + null); + Console.WriteLine($"Code: {res.Code}"); + Console.WriteLine($"Msg: {res.Msg}"); + } + catch (PitayaException e) + { + Logger.Error("Error sending RPC Call: {0}", e.Message); + } + } + // Confirm the RPC sending capabilities are working + } +} diff --git a/csharp/examples/sidecar/gen/Cluster.cs b/csharp/examples/sidecar/gen/Cluster.cs new file mode 100644 index 00000000..8131d033 --- /dev/null +++ b/csharp/examples/sidecar/gen/Cluster.cs @@ -0,0 +1,431 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: go-server/protos/cluster.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Protos { + + /// Holder for reflection information generated from go-server/protos/cluster.proto + public static partial class ClusterReflection { + + #region Descriptor + /// File descriptor for go-server/protos/cluster.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static ClusterReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Ch5nby1zZXJ2ZXIvcHJvdG9zL2NsdXN0ZXIucHJvdG8SBnByb3RvcyIVCgZS", + "UENNc2cSCwoDTXNnGAEgASgJIiMKBlJQQ1JlcxILCgNNc2cYASABKAkSDAoE", + "Q29kZRgCIAEoBUISWhBnby1zZXJ2ZXIvcHJvdG9zYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::Protos.RPCMsg), global::Protos.RPCMsg.Parser, new[]{ "Msg" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::Protos.RPCRes), global::Protos.RPCRes.Parser, new[]{ "Msg", "Code" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + /// + /// RPCMsg message to be sent using rpc + /// + public sealed partial class RPCMsg : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new RPCMsg()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Protos.ClusterReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCMsg() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCMsg(RPCMsg other) : this() { + msg_ = other.msg_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCMsg Clone() { + return new RPCMsg(this); + } + + /// Field number for the "Msg" field. + public const int MsgFieldNumber = 1; + private string msg_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Msg { + get { return msg_; } + set { + msg_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as RPCMsg); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(RPCMsg other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Msg != other.Msg) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Msg.Length != 0) hash ^= Msg.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Msg.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Msg); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Msg.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Msg); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Msg.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Msg); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(RPCMsg other) { + if (other == null) { + return; + } + if (other.Msg.Length != 0) { + Msg = other.Msg; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Msg = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Msg = input.ReadString(); + break; + } + } + } + } + #endif + + } + + /// + /// RPCRes is the rpc response + /// + public sealed partial class RPCRes : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new RPCRes()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::Protos.ClusterReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCRes() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCRes(RPCRes other) : this() { + msg_ = other.msg_; + code_ = other.code_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCRes Clone() { + return new RPCRes(this); + } + + /// Field number for the "Msg" field. + public const int MsgFieldNumber = 1; + private string msg_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Msg { + get { return msg_; } + set { + msg_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "Code" field. + public const int CodeFieldNumber = 2; + private int code_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int Code { + get { return code_; } + set { + code_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as RPCRes); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(RPCRes other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Msg != other.Msg) return false; + if (Code != other.Code) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Msg.Length != 0) hash ^= Msg.GetHashCode(); + if (Code != 0) hash ^= Code.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Msg.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Msg); + } + if (Code != 0) { + output.WriteRawTag(16); + output.WriteInt32(Code); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Msg.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Msg); + } + if (Code != 0) { + output.WriteRawTag(16); + output.WriteInt32(Code); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Msg.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Msg); + } + if (Code != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Code); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(RPCRes other) { + if (other == null) { + return; + } + if (other.Msg.Length != 0) { + Msg = other.Msg; + } + if (other.Code != 0) { + Code = other.Code; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Msg = input.ReadString(); + break; + } + case 16: { + Code = input.ReadInt32(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Msg = input.ReadString(); + break; + } + case 16: { + Code = input.ReadInt32(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/sidecar/remotes/TestRemote.cs b/csharp/examples/sidecar/remotes/TestRemote.cs new file mode 100644 index 00000000..b7d0f08f --- /dev/null +++ b/csharp/examples/sidecar/remotes/TestRemote.cs @@ -0,0 +1,18 @@ +using System.Threading.Tasks; +using NPitaya.Models; + +namespace exampleapp.remotes +{ +#pragma warning disable 1998 + class TestRemote : BaseRemote + { + public async Task Remote(Protos.RPCMsg msg) + { + var response = new Protos.RPCMsg + { + Msg = $"hello from csharp :) {System.Guid.NewGuid().ToString()}" + }; + return response; + } + } +} diff --git a/csharp/examples/sidecar/sidecar.csproj b/csharp/examples/sidecar/sidecar.csproj new file mode 100644 index 00000000..9aff3d37 --- /dev/null +++ b/csharp/examples/sidecar/sidecar.csproj @@ -0,0 +1,12 @@ + + + + Exe + netcoreapp6 + + + + + + + diff --git a/csharp/examples/unity/.gitignore b/csharp/examples/unity/.gitignore new file mode 100644 index 00000000..72c27e4f --- /dev/null +++ b/csharp/examples/unity/.gitignore @@ -0,0 +1,71 @@ +# This .gitignore file should be placed at the root of your Unity project directory +# +# Get latest from https://github.com/github/gitignore/blob/master/Unity.gitignore +# +/[Ll]ibrary/ +/[Tt]emp/ +/[Oo]bj/ +/[Bb]uild/ +/[Bb]uilds/ +/[Ll]ogs/ +/[Uu]ser[Ss]ettings/ + +# MemoryCaptures can get excessive in size. +# They also could contain extremely sensitive data +/[Mm]emoryCaptures/ + +# Asset meta data should only be ignored when the corresponding asset is also ignored +!/[Aa]ssets/**/*.meta + +# Uncomment this line if you wish to ignore the asset store tools plugin +# /[Aa]ssets/AssetStoreTools* + +# Autogenerated Jetbrains Rider plugin +/[Aa]ssets/Plugins/Editor/JetBrains* + +# Visual Studio cache directory +.vs/ + +# Gradle cache directory +.gradle/ + +# Autogenerated VS/MD/Consulo solution and project files +ExportedObj/ +.consulo/ +*.csproj +*.unityproj +*.sln +*.suo +*.tmp +*.user +*.userprefs +*.pidb +*.booproj +*.svd +*.pdb +*.mdb +*.opendb +*.VC.db + +# Unity3D generated meta files +*.pidb.meta +*.pdb.meta +*.mdb.meta + +# Unity3D generated file on crash reports +sysinfo.txt + +# Builds +*.apk +*.aab +*.unitypackage + +# Crashlytics generated file +crashlytics-build.properties + +# Packed Addressables +/[Aa]ssets/[Aa]ddressable[Aa]ssets[Dd]ata/*/*.bin* + +# Temporary auto-generated Android Assets +/[Aa]ssets/[Ss]treamingAssets/aa.meta +/[Aa]ssets/[Ss]treamingAssets/aa/* diff --git a/csharp/examples/unity/.vsconfig b/csharp/examples/unity/.vsconfig new file mode 100644 index 00000000..aade28f6 --- /dev/null +++ b/csharp/examples/unity/.vsconfig @@ -0,0 +1,6 @@ +{ + "version": "1.0", + "components": [ + "Microsoft.VisualStudio.Workload.ManagedGame" + ] +} diff --git a/csharp/examples/unity/Assets/NuGet.config b/csharp/examples/unity/Assets/NuGet.config new file mode 100644 index 00000000..a3b60ed4 --- /dev/null +++ b/csharp/examples/unity/Assets/NuGet.config @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp/examples/unity/Assets/NuGet.config.meta b/csharp/examples/unity/Assets/NuGet.config.meta new file mode 100644 index 00000000..a51dc7bf --- /dev/null +++ b/csharp/examples/unity/Assets/NuGet.config.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: bc8871ed28e00f949981463b24a474e5 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/NuGet.meta b/csharp/examples/unity/Assets/NuGet.meta new file mode 100644 index 00000000..260915e8 --- /dev/null +++ b/csharp/examples/unity/Assets/NuGet.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 217cb7caed5f7fb49b339428b1d80974 +folderAsset: yes +timeCreated: 1510280316 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/NuGet/Editor.meta b/csharp/examples/unity/Assets/NuGet/Editor.meta new file mode 100644 index 00000000..3b6fd6bc --- /dev/null +++ b/csharp/examples/unity/Assets/NuGet/Editor.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: b3fad56c531ac5a4db190a745f589a8e +folderAsset: yes +timeCreated: 1510280304 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/NuGet/Editor/NugetForUnity.dll.meta b/csharp/examples/unity/Assets/NuGet/Editor/NugetForUnity.dll.meta new file mode 100644 index 00000000..833aac7d --- /dev/null +++ b/csharp/examples/unity/Assets/NuGet/Editor/NugetForUnity.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: 8dc1be91775c4bb469f6b74cef450eaa +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/NuGet/LICENSE b/csharp/examples/unity/Assets/NuGet/LICENSE new file mode 100644 index 00000000..e5e72104 --- /dev/null +++ b/csharp/examples/unity/Assets/NuGet/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Patrick McCarthy + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/csharp/examples/unity/Assets/NuGet/LICENSE.meta b/csharp/examples/unity/Assets/NuGet/LICENSE.meta new file mode 100644 index 00000000..9de0ac8d --- /dev/null +++ b/csharp/examples/unity/Assets/NuGet/LICENSE.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1d9014b99ad06af428514a5902d29ff3 +timeCreated: 1573248500 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/NuGet/README.pdf b/csharp/examples/unity/Assets/NuGet/README.pdf new file mode 100644 index 00000000..e67f9fa5 Binary files /dev/null and b/csharp/examples/unity/Assets/NuGet/README.pdf differ diff --git a/csharp/examples/unity/Assets/NuGet/README.pdf.meta b/csharp/examples/unity/Assets/NuGet/README.pdf.meta new file mode 100644 index 00000000..e95001a0 --- /dev/null +++ b/csharp/examples/unity/Assets/NuGet/README.pdf.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 83c5d2001771f15429a88d67e81366d6 +timeCreated: 1517876157 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/NuGet/Resources.meta b/csharp/examples/unity/Assets/NuGet/Resources.meta new file mode 100644 index 00000000..49a5e3b4 --- /dev/null +++ b/csharp/examples/unity/Assets/NuGet/Resources.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 1738075a39a390447b7a620ca6962142 +folderAsset: yes +timeCreated: 1510280362 +licenseType: Free +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/NuGet/Resources/defaultIcon.png b/csharp/examples/unity/Assets/NuGet/Resources/defaultIcon.png new file mode 100644 index 00000000..a16cc198 Binary files /dev/null and b/csharp/examples/unity/Assets/NuGet/Resources/defaultIcon.png differ diff --git a/csharp/examples/unity/Assets/NuGet/Resources/defaultIcon.png.meta b/csharp/examples/unity/Assets/NuGet/Resources/defaultIcon.png.meta new file mode 100644 index 00000000..d23111ab --- /dev/null +++ b/csharp/examples/unity/Assets/NuGet/Resources/defaultIcon.png.meta @@ -0,0 +1,88 @@ +fileFormatVersion: 2 +guid: eec19781926cd2248b7c9abfde8db555 +TextureImporter: + fileIDToRecycleName: {} + externalObjects: {} + serializedVersion: 9 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: -1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: 1 + wrapV: 1 + wrapW: 1 + nPOTScale: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: 215e43cda847e6d44af8b40376eeed8a + vertices: [] + indices: + edges: [] + weights: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Packages.meta b/csharp/examples/unity/Assets/Packages.meta new file mode 100644 index 00000000..b657594f --- /dev/null +++ b/csharp/examples/unity/Assets/Packages.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ef303005113ed2e4e94e7970eb4bca20 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0.meta b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0.meta new file mode 100644 index 00000000..5f71c44d --- /dev/null +++ b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e57a78a3b95a7404bbae3a931456b241 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/.signature.p7s b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/.signature.p7s new file mode 100644 index 00000000..6e4a101d Binary files /dev/null and b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/.signature.p7s differ diff --git a/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/DogStatsD-CSharp-Client.6.0.0.nupkg b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/DogStatsD-CSharp-Client.6.0.0.nupkg new file mode 100644 index 00000000..34fd5976 Binary files /dev/null and b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/DogStatsD-CSharp-Client.6.0.0.nupkg differ diff --git a/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/DogStatsD-CSharp-Client.6.0.0.nupkg.meta b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/DogStatsD-CSharp-Client.6.0.0.nupkg.meta new file mode 100644 index 00000000..4d092335 --- /dev/null +++ b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/DogStatsD-CSharp-Client.6.0.0.nupkg.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 96f7713468657254e91fcfb4a0f456e1 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib.meta b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib.meta new file mode 100644 index 00000000..4d6ca2a9 --- /dev/null +++ b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 529710e0d43f30a40bf52b9aef523aa7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0.meta b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0.meta new file mode 100644 index 00000000..40e82566 --- /dev/null +++ b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b9075979055aafa4f8f019bc5ed47d6d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0/StatsdClient.dll.meta b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0/StatsdClient.dll.meta new file mode 100644 index 00000000..92b19140 --- /dev/null +++ b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0/StatsdClient.dll.meta @@ -0,0 +1,33 @@ +fileFormatVersion: 2 +guid: 0565a60bca879594b9b87be19abdab00 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0/StatsdClient.xml b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0/StatsdClient.xml new file mode 100644 index 00000000..c4604371 --- /dev/null +++ b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0/StatsdClient.xml @@ -0,0 +1,947 @@ + + + + StatsdClient + + + + + The advanced configuration options for DogStatsdService. + + + + + Initializes a new instance of the class. + + + + + Gets or sets a value defining the maximum number of metrics in the queue + (Metrics are sent asynchronously using a queue). + A small value reduces memory usage whereas an higher value reduces + latency (When is null) or the number of messages + dropped (When is not null). + + + + + Gets or sets a value defining the maximum duration a call can block. + If there are more metrics than `MaxMetricsInAsyncQueue` waiting to be sent: + - if is null, the metric send by a call to a + or method will be dropped. + - If is not null, the metric send by a call to a + or method will block for at most + duration. + + + + + Gets or sets a value defining how long + DogStatsD waits before sending a not full buffer (Metrics are buffered before sent). + + + + + Gets or sets a value defining how long to wait when the UDS buffer is full + (SocketError.NoBufferSpaceAvailable). A null value results in + dropping the metric. + + + + + Gets or sets a value defining the duration between two telemetry flushes. + When this value is set at null, telemetry is disabled. + + + + + Gets or sets a value defining the telemetry endpoint. INTERNAL USAGE ONLY. + + + + + AggregatorFlusher is responsible for flushing the aggregated `MetricStats` instances. + + + + + Store all aggregators + + + + + Aggregate instances of type + by summing the value by . + + + + + Aggregate `StatsMetric` instances of type `Gauge` by by keeping the last value. + + + + + Dictionary Key for `MetricStats`. + It is more efficient to use `MetricStatsKey` than creating a string from metric name and tags. + + + + + Aggregate `StatsMetric` instances of type `Set` by keeping the unique values. + + + + + Append string values to a fixed size bytes buffer. + + + + + BufferBuilderHandler forwards metrics to ITransport and update telemetry. + + + + + IStatsBufferizeFactory is a factory for StatsBufferize. + It is used to test StatsBufferize. + + + + + StatsBufferize bufferizes metrics before sending them. + + + + + Define the configuration for the client side aggregation. + + + + + Gets or sets the maximum number of unique stats before flushing. + + + + + Gets or sets the maximum interval duration between two flushes. + + + + + The status of the service check. + + + + + Status OK + + + + + Status Warning + + + + + Status Critical + + + + + Status Unknown + + + + + DogStatsd is a collection of static methods that provide the same feature as DogStatsdService. + + + + + Gets the telemetry counters + + The telemetry counters. + + + + Configures the instance. + Must be called before any other methods. + + The value of the config. + + + + Records an event. + + The title of the event. + The text body of the event. + error, warning, success, or info (defaults to info). + A key to use for aggregating events. + The source type name. + The epoch timestamp for the event (defaults to the current time from the DogStatsD server). + Specifies the priority of the event (normal or low). + The name of the host. + Array of tags to be added to the data. + + + + Adjusts the specified counter by a given delta. + + The name of the metric. + A given delta. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Increments the specified counter. + + The name of the metric. + The amount of increment. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Decrements the specified counter. + + The name of the metric. + The amount of decrement. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records the latest fixed value for the specified named gauge. + + The name of the metric. + The value of the gauge. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records a value for the specified named histogram. + + The name of the metric. + The value of the histogram. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records a value for the specified named distribution. + + The name of the metric. + The value of the distribution. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records a value for the specified set. + + The name of the metric. + The value to set. + Percentage of metric to be sent. + Array of tags to be added to the data. + The type of the value. + + + + Records a value for the specified set. + + The name of the metric. + The value to set. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records an execution time in milliseconds. + + The name of the metric. + The time in millisecond. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Creates a timer that records the execution time until Dispose is called on the returned value. + + The name of the metric. + Percentage of metric to be sent. + Array of tags to be added to the data. + A disposable object that records the execution time until Dispose is called. + + + + Records an execution time for the given action. + + The given action. + The name of the metric. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records an execution time for the given function. + + The given function. + The name of the metric. + Percentage of metric to be sent. + Array of tags to be added to the data. + The type of the returned value of . + The returned value of . + + + + Records a run status for the specified named service check. + + The name of the service check. + A constant describing the service status. + The epoch timestamp for the service check (defaults to the current time from the DogStatsD server). + The hostname to associate with the service check. + Array of tags to be added to the data. + Additional information or a description of why the status occurred. + + + + Flushes all metrics. + + + + + Disposes the instance of DogStatsdService. + Flushes all metrics. + + + + + DogStatsdEndPoint is a DogStatsd endpoint (UDP or UDS). + + + + + Gets or sets a value defining the name of the endpoint + + + + + Gets or sets a value defining the port number if any + + + + + Gets or sets the name of the pipe. INTERNAL USAGE ONLY. + + + + + AreEquals returns whether `this` and `endPoint` have the same values + + The endpoint to compare with `this` + Returns whether `this` and `endPoint` have the same values + + + + DogStatsdService is a DogStatsD client. + Dispose must be called to flush all the metrics. + + + + + Gets the telemetry counters + + The telemetry counters. + + + + Configures the instance. + Must be called before any other methods. + + The value of the config. + + + + Records an event. + + The title of the event. + The text body of the event. + error, warning, success, or info (defaults to info). + A key to use for aggregating events. + The source type name. + The epoch timestamp for the event (defaults to the current time from the DogStatsD server). + Specifies the priority of the event (normal or low). + The name of the host. + Array of tags to be added to the data. + + + + Adjusts the specified counter by a given delta. + + The name of the metric. + A given delta. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Increments the specified counter. + + The name of the metric. + The amount of increment. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Decrements the specified counter. + + The name of the metric. + The amount of decrement. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records the latest fixed value for the specified named gauge. + + The name of the metric. + The value of the gauge. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records a value for the specified named histogram. + + The name of the metric. + The value of the histogram. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records a value for the specified named distribution. + + The name of the metric. + The value of the distribution. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records a value for the specified set. + + The name of the metric. + The value to set. + Percentage of metric to be sent. + Array of tags to be added to the data. + The type of the value. + + + + Records a value for the specified set. + + The name of the metric. + The value to set. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records an execution time in milliseconds. + + The name of the metric. + The time in millisecond. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Creates a timer that records the execution time until Dispose is called on the returned value. + + The name of the metric. + Percentage of metric to be sent. + Array of tags to be added to the data. + A disposable object that records the execution time until Dispose is called. + + + + Records an execution time for the given action. + + The given action. + The name of the metric. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records an execution time for the given function. + + The given function. + The name of the metric. + Percentage of metric to be sent. + Array of tags to be added to the data. + The type of the returned value of . + The returned value of . + + + + Records a run status for the specified named service check. + + The name of the service check. + A constant describing the service status. + The epoch timestamp for the service check (defaults to the current time from the DogStatsD server). + The hostname to associate with the service check. + Array of tags to be added to the data. + Additional information or a description of why the status occurred. + + + + Flushes all metrics. + + + + + Disposes an instance of DogStatsdService. + Flushes all metrics. + + + + + IDogStatsd is an interface over DogStatsdService. + + + + + Gets the telemetry counters + + The telemetry counters. + + + + Configures the instance. + Must be called before any other methods. + + The value of the config. + + + + Adjusts the specified counter by a given delta. + + The name of the metric. + A given delta. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Decrements the specified counter. + + The name of the metric. + The amount of decrement. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records an event. + + The title of the event. + The text body of the event. + error, warning, success, or info (defaults to info). + A key to use for aggregating events. + The source type name. + The epoch timestamp for the event (defaults to the current time from the DogStatsD server). + Specifies the priority of the event (normal or low). + The name of the host. + Array of tags to be added to the data. + + + + Records the latest fixed value for the specified named gauge. + + The name of the metric. + The value of the gauge. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records a value for the specified named histogram. + + The name of the metric. + The value of the histogram. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records a value for the specified named distribution. + + The name of the metric. + The value of the distribution. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Increments the specified counter. + + The name of the metric. + The amount of increment. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records a value for the specified set. + + The name of the metric. + The value to set. + Percentage of metric to be sent. + Array of tags to be added to the data. + The type of the value. + + + + Records a value for the specified set. + + The name of the metric. + The value to set. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Creates a timer that records the execution time until Dispose is called on the returned value. + + The name of the metric. + Percentage of metric to be sent. + Array of tags to be added to the data. + A disposable object that records the execution time until Dispose is called. + + + + Records an execution time for the given action. + + The given action. + The name of the metric. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records an execution time for the given function. + + The given function. + The name of the metric. + Percentage of metric to be sent. + Array of tags to be added to the data. + The type of the returned value of . + The returned value of . + + + + Records an execution time in milliseconds. + + The name of the metric. + The time in millisecond. + Percentage of metric to be sent. + Array of tags to be added to the data. + + + + Records a run status for the specified named service check. + + The name of the service check. + A constant describing the service status. + The epoch timestamp for the service check (defaults to the current time from the DogStatsD server). + The hostname to associate with the service check. + Array of tags to be added to the data. + Additional information or a description of why the status occurred. + + + + ITelemetryCounters contains the telemetry counters. + + + + + Gets the number of metrics sent. + + The number of metrics sent. + + + + Gets the number of events sent. + + The number of events sent. + + + + Gets the number of service checks sent. + + The number of service checks sent. + + + + Gets the total number of bytes sent. + + The total number of bytes sent. + + + + Gets the total number of bytes dropped. + + The total number of bytes dropped. + + + + Gets the number of packets (UDP or UDS) sent. + + The number of packets (UDP or UDS) sent. + + + + Gets the number of packets (UDP or UDS) dropped. + + The number of packets (UDP or UDS) dropped. + + + + Gets the number of packets (UDP or UDS) dropped because the queue is full. + + The number of packets (UDP or UDS) dropped because the queue is full. + + + + Stats stores the data for a metric or a service check or an event. + The field `Metric`, `ServiceCheck` and `Event` are structures for performance reasons. These + fields are embeded inside Stats and so do not require extra allocations. + + + + + Store the data for an event. + + + + + Store the data for a metric. + + + + + Store the data for a service check. + + + + + StatsdBuilder builds an instance of `Statsd` from StatsdConfig. + + + + + The configuration options for DogStatsdService. + + + + + The default port for UDP. + + + + + The default UDP maximum packet size. + + + + + The name of the environment variable defining the global tags to be applied to every metric, event, and service check. + + + + + The name of the environment variable defining the port of the targeted StatsD server. + + + + + The name of the environment variable defining the host name of the targeted StatsD server. + + + + + The name of the environment variable defining the name of the pipe. INTERNAL USAGE ONLY. + + + + + The name of the environment variable defining the service name + + + + + The name of the environment variable defining the environment name + + + + + The name of the environment variable defining the version of the service + + + + + Initializes a new instance of the class. + + + + + Gets or sets the host name of the targeted StatsD server. + + The host name of the targeted StatsD server. + + + + Gets or sets the name of the pipe. INTERNAL USAGE ONLY. + + + + + Gets or sets the port of the targeted StatsD server. + + The port of the targeted StatsD server. + + + + Gets or sets the maximum UDP packet size. + + The maximum UDP packet size. + + + + Gets or sets the maximum Unix domain socket packet size. + + The maximum Unix domain socket packet size. + + + + Gets or sets a value indicating whether we truncate the metric if it is too long. + + The value indicating whether we truncate the metric if it is too long. + + + + Gets or sets the prefix to apply to every metric, event, and service check. + + The prefix to apply to every metric, event, and service check. + + + + Gets the advanced configuration. + + The advanced configuration + + + + Gets or sets the environment tag + + + + + Gets or sets the service version tag + + + + + Gets or sets the service name tag + + + + + Gets or sets the global tags to be applied to every metric, event, and service check. + + The global tags to be applied to every metric, event, and service check. + + + + Gets or sets a value defining the client side aggregation config. + If the value is null, the client side aggregation is not enabled. + + + + + Route `Stats` instances. + Route a metric of type , + and respectively to , + and . + Others stats are routed to . + + + + + Telemetry sends telemetry metrics. + + + + + Send the buffer. + Must be thread safe as it is called to send metrics and the telemetry. + + + + + Send the buffer. + Must be thread safe. + + + + + Send the buffer. + Must be thread safe. + + + + + AsynchronousWorker performs tasks asynchronously. + `handler` must be thread safe if `workerThreadCount` > 1. + + + + + ConcurrentBoundedBlockingQueue is the same as ConcurrentBoundedQueue but + it waits for `waitTimeout` before dropping the value when the queue is full. + + + + + ConcurrentBoundedQueue is a ConcurrentQueue with a bounded number of items. + Note: Value is not enqueued when the queue is full. + + + + + Called when a new value is ready to be handled by the worker. + + + + + Called when the worker is waiting for new value to handle. + + Return true to make the worker in a sleep state, false otherwise. + + + + Called when AsynchronousWorker request a flush operation. + + + + + Simple wrapper arround ManualResetEventSlim. + + + + diff --git a/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0/StatsdClient.xml.meta b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0/StatsdClient.xml.meta new file mode 100644 index 00000000..56f4f38c --- /dev/null +++ b/csharp/examples/unity/Assets/Packages/DogStatsD-CSharp-Client.6.0.0/lib/netstandard2.0/StatsdClient.xml.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 6d4ea5889dcfa9e4f9c24909f07b83b0 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins.meta b/csharp/examples/unity/Assets/Plugins.meta new file mode 100644 index 00000000..e58b95e4 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5f7585bafbca2474bbcbdd07e00436a9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc.meta b/csharp/examples/unity/Assets/Plugins/Grpc.meta new file mode 100644 index 00000000..77452384 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9cdc0161bcd0f1245a0f3281854480b2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf.meta new file mode 100644 index 00000000..c9d3ca96 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4b6ebd913ac610041b63fc847ee96302 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf/lib.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf/lib.meta new file mode 100644 index 00000000..d415abf6 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf/lib.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e4ab5b3f8a676a84a9eb3ffcf1e8138d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf/lib/net45.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf/lib/net45.meta new file mode 100644 index 00000000..b7670b6f --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf/lib/net45.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4c50e24955a9a294b99ad097ae2e252a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf/lib/net45/Google.Protobuf.dll.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf/lib/net45/Google.Protobuf.dll.meta new file mode 100644 index 00000000..d6a53783 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Google.Protobuf/lib/net45/Google.Protobuf.dll.meta @@ -0,0 +1,30 @@ +fileFormatVersion: 2 +guid: 286edf5aec6aae64697e5e8b7ab9b60e +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api.meta new file mode 100644 index 00000000..f5d5149c --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 9b4ba511bab164bf9a5d0db8bb681b05 +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib.meta new file mode 100644 index 00000000..88c1aedb --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 21a3894045fc74e85a09ab84c0e35c3a +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45.meta new file mode 100644 index 00000000..8012e3d5 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 9fd1c7cd7b6ed4d5285de90a332fb93e +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45/Grpc.Core.Api.dll.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45/Grpc.Core.Api.dll.meta new file mode 100644 index 00000000..7b939f86 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45/Grpc.Core.Api.dll.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: c9bf7237d50ec4e99ba7d2c153b80e8f +timeCreated: 1531219386 +licenseType: Free +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45/Grpc.Core.Api.xml b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45/Grpc.Core.Api.xml new file mode 100644 index 00000000..59afcbc4 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45/Grpc.Core.Api.xml @@ -0,0 +1,2732 @@ + + + + Grpc.Core.Api + + + + + Asynchronous authentication interceptor for . + + The interceptor context. + Metadata to populate with entries that will be added to outgoing call's headers. + + + + + Context for an RPC being intercepted by . + + + + + Initializes a new instance of AuthInterceptorContext. + + + + + The fully qualified service URL for the RPC being called. + + + + + The method name of the RPC being called. + + + + + Provides an abstraction over the callback providers + used by AsyncUnaryCall, AsyncDuplexStreamingCall, etc + + + + + Return type for client streaming calls. + + Request message type for this call. + Response message type for this call. + + + + Creates a new AsyncClientStreamingCall object with the specified properties. + + Stream of request values. + The response of the asynchronous call. + Response headers of the asynchronous call. + Delegate returning the status of the call. + Delegate returning the trailing metadata of the call. + Delegate to invoke when Dispose is called on the call object. + + + + Creates a new AsyncClientStreamingCall object with the specified properties. + + Stream of request values. + The response of the asynchronous call. + Response headers of the asynchronous call. + Delegate returning the status of the call. + Delegate returning the trailing metadata of the call. + Delegate to invoke when Dispose is called on the call object. + State object for use with the callback parameters. + + + + Asynchronous call result. + + + + + Asynchronous access to response headers. + + + + + Async stream to send streaming requests. + + + + + Allows awaiting this object directly. + + + + + + Gets the call status if the call has already finished. + Throws InvalidOperationException otherwise. + + + + + Gets the call trailing metadata if the call has already finished. + Throws InvalidOperationException otherwise. + + + + + Provides means to cleanup after the call. + If the call has already finished normally (request stream has been completed and call result has been received), doesn't do anything. + Otherwise, requests cancellation of the call which should terminate all pending async operations associated with the call. + As a result, all resources being used by the call should be released eventually. + + + Normally, there is no need for you to dispose the call unless you want to utilize the + "Cancel" semantics of invoking Dispose. + + + + + Return type for bidirectional streaming calls. + + Request message type for this call. + Response message type for this call. + + + + Creates a new AsyncDuplexStreamingCall object with the specified properties. + + Stream of request values. + Stream of response values. + Response headers of the asynchronous call. + Delegate returning the status of the call. + Delegate returning the trailing metadata of the call. + Delegate to invoke when Dispose is called on the call object. + + + + Creates a new AsyncDuplexStreamingCall object with the specified properties. + + Stream of request values. + Stream of response values. + Response headers of the asynchronous call. + Delegate returning the status of the call. + Delegate returning the trailing metadata of the call. + Delegate to invoke when Dispose is called on the call object. + State object for use with the callback parameters. + + + + Async stream to read streaming responses. + + + + + Async stream to send streaming requests. + + + + + Asynchronous access to response headers. + + + + + Gets the call status if the call has already finished. + Throws InvalidOperationException otherwise. + + + + + Gets the call trailing metadata if the call has already finished. + Throws InvalidOperationException otherwise. + + + + + Provides means to cleanup after the call. + If the call has already finished normally (request stream has been completed and response stream has been fully read), doesn't do anything. + Otherwise, requests cancellation of the call which should terminate all pending async operations associated with the call. + As a result, all resources being used by the call should be released eventually. + + + Normally, there is no need for you to dispose the call unless you want to utilize the + "Cancel" semantics of invoking Dispose. + + + + + Return type for server streaming calls. + + Response message type for this call. + + + + Creates a new AsyncDuplexStreamingCall object with the specified properties. + + Stream of response values. + Response headers of the asynchronous call. + Delegate returning the status of the call. + Delegate returning the trailing metadata of the call. + Delegate to invoke when Dispose is called on the call object. + + + + Creates a new AsyncDuplexStreamingCall object with the specified properties. + + Stream of response values. + Response headers of the asynchronous call. + Delegate returning the status of the call. + Delegate returning the trailing metadata of the call. + Delegate to invoke when Dispose is called on the call object. + State object for use with the callback parameters. + + + + Async stream to read streaming responses. + + + + + Asynchronous access to response headers. + + + + + Gets the call status if the call has already finished. + Throws InvalidOperationException otherwise. + + + + + Gets the call trailing metadata if the call has already finished. + Throws InvalidOperationException otherwise. + + + + + Provides means to cleanup after the call. + If the call has already finished normally (response stream has been fully read), doesn't do anything. + Otherwise, requests cancellation of the call which should terminate all pending async operations associated with the call. + As a result, all resources being used by the call should be released eventually. + + + Normally, there is no need for you to dispose the call unless you want to utilize the + "Cancel" semantics of invoking Dispose. + + + + + Extension methods for . + + + + + Advances the stream reader to the next element in the sequence, returning the result asynchronously. + + The message type. + The stream reader. + + Task containing the result of the operation: true if the reader was successfully advanced + to the next element; false if the reader has passed the end of the sequence. + + + + + Return type for single request - single response call. + + Response message type for this call. + + + + Creates a new AsyncUnaryCall object with the specified properties. + + The response of the asynchronous call. + Response headers of the asynchronous call. + Delegate returning the status of the call. + Delegate returning the trailing metadata of the call. + Delegate to invoke when Dispose is called on the call object. + + + + Creates a new AsyncUnaryCall object with the specified properties. + + The response of the asynchronous call. + Response headers of the asynchronous call. + Delegate returning the status of the call. + Delegate returning the trailing metadata of the call. + Delegate to invoke when Dispose is called on the call object. + State object for use with the callback parameters. + + + + Asynchronous call result. + + + + + Asynchronous access to response headers. + + + + + Allows awaiting this object directly. + + + + + Gets the call status if the call has already finished. + Throws InvalidOperationException otherwise. + + + + + Gets the call trailing metadata if the call has already finished. + Throws InvalidOperationException otherwise. + + + + + Provides means to cleanup after the call. + If the call has already finished normally (request stream has been completed and call result has been received), doesn't do anything. + Otherwise, requests cancellation of the call which should terminate all pending async operations associated with the call. + As a result, all resources being used by the call should be released eventually. + + + Normally, there is no need for you to dispose the call unless you want to utilize the + "Cancel" semantics of invoking Dispose. + + + + + Authentication context for a call. + AuthContext is the only reliable source of truth when it comes to authenticating calls. + Using any other call/context properties for authentication purposes is wrong and inherently unsafe. + Note: experimental API that can change or be removed without any prior notice. + + + + + Initializes a new instance of the class. + + Peer identity property name. + Multimap of auth properties by name. + + + + Returns true if the peer is authenticated. + + + + + Gets the name of the property that indicates the peer identity. Returns null + if the peer is not authenticated. + + + + + Gets properties that represent the peer identity (there can be more than one). Returns an empty collection + if the peer is not authenticated. + + + + + Gets the auth properties of this context. + + + + + Returns the auth properties with given name (there can be more than one). + If no properties of given name exist, an empty collection will be returned. + + + + + A property of an . + Note: experimental API that can change or be removed without any prior notice. + + + + + Gets the name of the property. + + + + + Gets the string value of the property. + + + + + Gets the binary value of the property. + + + + + Creates an instance of AuthProperty. + + the name + the binary value of the property + + + + Gets the binary value of the property (without making a defensive copy). + + + + + Creates and instance of AuthProperty without making a defensive copy of valueBytes. + + + + + Specifies the location of the service bind method for a gRPC service. + The bind method is typically generated code and is used to register a service's + methods with the server on startup. + + The bind method signature takes a and an optional + instance of the service base class, e.g. static void BindService(ServiceBinderBase, GreeterService). + + + + + Initializes a new instance of the class. + + The type the service bind method is defined on. + The name of the service bind method. + + + + Gets the type the service bind method is defined on. + + + + + Gets the name of the service bind method. + + + + + Client-side call credentials. Provide authorization with per-call granularity. + + + + + Composes multiple CallCredentials objects into + a single CallCredentials object. + + credentials to compose + The new CompositeCallCredentials + + + + Creates a new instance of CallCredentials class from an + interceptor that can attach metadata to outgoing calls. + + authentication interceptor + + + + Populates call credentials configurator with this instance's configuration. + End users never need to invoke this method as it is part of internal implementation. + + + + + Base class for objects that can consume configuration from CallCredentials objects. + Note: experimental API that can change or be removed without any prior notice. + + + + + Consumes configuration for composite call credentials. + + + + + Consumes configuration for call credentials created from AsyncAuthInterceptor + + + + + Flags to enable special call behaviors (client-side only). + + + + + The call is idempotent (retrying the call doesn't change the outcome of the operation). + + + + + If channel is in ChannelState.TransientFailure, attempt waiting for the channel to recover + instead of failing the call immediately. + + + + + The call is cacheable. gRPC is free to use GET verb */ + + + + + Call invoker that throws NotImplementedException for all requests. + + + + + Abstraction of client-side RPC invocation. + + + + + Invokes a simple remote call in a blocking fashion. + + + + + Invokes a simple remote call asynchronously. + + + + + Invokes a server streaming call asynchronously. + In server streaming scenario, client sends on request and server responds with a stream of responses. + + + + + Invokes a client streaming call asynchronously. + In client streaming scenario, client sends a stream of requests and server responds with a single response. + + + + + Invokes a duplex streaming call asynchronously. + In duplex streaming scenario, client sends a stream of requests and server responds with a stream of responses. + The response stream is completely independent and both side can be sending messages at the same time. + + + + + Options for calls made by client. + + + + + Creates a new instance of CallOptions struct. + + Headers to be sent with the call. + Deadline for the call to finish. null means no deadline. + Can be used to request cancellation of the call. + Write options that will be used for this call. + Context propagation token obtained from . + Credentials to use for this call. + + + + Headers to send at the beginning of the call. + + + + + Call deadline. + + + + + Token that can be used for cancelling the call on the client side. + Cancelling the token will request cancellation + of the remote call. Best effort will be made to deliver the cancellation + notification to the server and interaction of the call with the server side + will be terminated. Unless the call finishes before the cancellation could + happen (there is an inherent race), + the call will finish with StatusCode.Cancelled status. + + + + + Write options that will be used for this call. + + + + + Token for propagating parent call context. + + + + + Credentials to use for this call. + + + + + If true and channel is in ChannelState.TransientFailure, the call will attempt waiting for the channel to recover + instead of failing immediately (which is the default "FailFast" semantics). + Note: experimental API that can change or be removed without any prior notice. + + + + + Flags to use for this call. + + + + + Returns new instance of with + Headers set to the value provided. Values of all other fields are preserved. + + The headers. + + + + Returns new instance of with + Deadline set to the value provided. Values of all other fields are preserved. + + The deadline. + + + + Returns new instance of with + CancellationToken set to the value provided. Values of all other fields are preserved. + + The cancellation token. + + + + Returns new instance of with + WriteOptions set to the value provided. Values of all other fields are preserved. + + The write options. + + + + Returns new instance of with + PropagationToken set to the value provided. Values of all other fields are preserved. + + The context propagation token. + + + + Returns new instance of with + Credentials set to the value provided. Values of all other fields are preserved. + + The call credentials. + + + + Returns new instance of with "WaitForReady" semantics enabled/disabled. + . + Note: experimental API that can change or be removed without any prior notice. + + + + + Returns new instance of with + Flags set to the value provided. Values of all other fields are preserved. + + The call flags. + + + + Base class for gRPC channel. Channels are an abstraction of long-lived connections to remote servers. + + + + + Initializes a new instance of class that connects to a specific host. + + Target of the channel. + + + The original target used to create the channel. + + + + Create a new for the channel. + + A new . + + + + Shuts down the channel cleanly. It is strongly recommended to shutdown + the channel once you stopped using it. + + + Guidance for implementors: + This method doesn't wait for all calls on this channel to finish (nor does + it have to explicitly cancel all outstanding calls). It is user's responsibility to make sure + all the calls on this channel have finished (successfully or with an error) + before shutting down the channel to ensure channel shutdown won't impact + the outcome of those remote calls. + + + + Provides implementation of a non-virtual public member. + + + + Client-side channel credentials. Used for creation of a secure channel. + + + + + Creates a new instance of channel credentials + + + + + Returns instance of credentials that provides no security and + will result in creating an unsecure channel with no encryption whatsoever. + + + + + Returns instance of credentials that provides SSL security. + + These credentials are the same as creating without parameters. + Apps that are using Grpc.Core can create directly to customize + the secure SSL credentials. + + + + + + Creates a new instance of ChannelCredentials class by composing + given channel credentials with call credentials. + + Channel credentials. + Call credentials. + The new composite ChannelCredentials + + + + Populates channel credentials configurator with this instance's configuration. + End users never need to invoke this method as it is part of internal implementation. + + + + + Returns true if this credential type allows being composed by CompositeCredentials. + + + + + Credentials that allow composing one object and + one or more objects into a single . + + + + + Initializes a new instance of CompositeChannelCredentials class. + The resulting credentials object will be composite of all the credentials specified as parameters. + + channelCredentials to compose + channelCredentials to compose + + + + Base class for objects that can consume configuration from CallCredentials objects. + Note: experimental API that can change or be removed without any prior notice. + + + + + Configures the credentials to use insecure credentials. + + + + + Configures the credentials to use SslCredentials. + + + + + Configures the credentials to use composite channel credentials (a composite of channel credentials and call credentials). + + + + + Generic base class for client-side stubs. + + + + + Initializes a new instance of ClientBase class that + throws NotImplementedException upon invocation of any RPC. + This constructor is only provided to allow creation of test doubles + for client classes (e.g. mocking requires a parameterless constructor). + + + + + Initializes a new instance of ClientBase class. + + The configuration. + + + + Initializes a new instance of ClientBase class. + + The channel to use for remote call invocation. + + + + Initializes a new instance of ClientBase class. + + The CallInvoker for remote call invocation. + + + + Creates a new client that sets host field for calls explicitly. + gRPC supports multiple "hosts" being served by a single server. + By default (if a client was not created by calling this method), + host null with the meaning "use default host" is used. + + + + + Creates a new instance of client from given ClientBaseConfiguration. + + + + + Base class for client-side stubs. + + + + + Initializes a new instance of ClientBase class that + throws NotImplementedException upon invocation of any RPC. + This constructor is only provided to allow creation of test doubles + for client classes (e.g. mocking requires a parameterless constructor). + + + + + Initializes a new instance of ClientBase class. + + The configuration. + + + + Initializes a new instance of ClientBase class. + + The channel to use for remote call invocation. + + + + Initializes a new instance of ClientBase class. + + The CallInvoker for remote call invocation. + + + + Gets the call invoker. + + + + + Gets the configuration. + + + + + Represents configuration of ClientBase. The class itself is visible to + subclasses, but contents are marked as internal to make the instances opaque. + The verbose name of this class was chosen to make name clash in generated code + less likely. + + + + + Creates a new instance of ClientBaseConfigurationInterceptor given the specified header and host interceptor function. + + + + + Options for . + + + + + The context propagation options that will be used by default. + + + + + Creates new context propagation options. + + If set to true parent call's deadline will be propagated to the child call. + If set to true parent call's cancellation token will be propagated to the child call. + + + true if parent call's deadline should be propagated to the child call. + + + true if parent call's cancellation token should be propagated to the child call. + + + + Token for propagating context of server side handlers to child calls. + In situations when a backend is making calls to another backend, + it makes sense to propagate properties like deadline and cancellation + token of the server call to the child call. + Underlying gRPC implementation may provide other "opaque" contexts (like tracing context) that + are not explicitly accesible via the public C# API, but this token still allows propagating them. + + + + + Provides access to the payload being deserialized when deserializing messages. + + + + + Get the total length of the payload in bytes. + + + + + Gets the entire payload as a newly allocated byte array. + Once the byte array is returned, the byte array becomes owned by the caller and won't be ever accessed or reused by gRPC again. + NOTE: Obtaining the buffer as a newly allocated byte array is the simplest way of accessing the payload, + but it can have important consequences in high-performance scenarios. + In particular, using this method usually requires copying of the entire buffer one extra time. + Also, allocating a new buffer each time can put excessive pressure on GC, especially if + the payload is more than 86700 bytes large (which means the newly allocated buffer will be placed in LOH, + and LOH object can only be garbage collected via a full ("stop the world") GC run). + NOTE: Deserializers are expected not to call this method (or other payload accessor methods) more than once per received message + (as there is no practical reason for doing so) and DeserializationContext implementations are free to assume so. + + byte array containing the entire payload. + + + + Gets the entire payload as a ReadOnlySequence. + The ReadOnlySequence is only valid for the duration of the deserializer routine and the caller must not access it after the deserializer returns. + Using the read only sequence is the most efficient way to access the message payload. Where possible it allows directly + accessing the received payload without needing to perform any buffer copying or buffer allocations. + NOTE: When using this method, it is recommended to use C# 7.2 compiler to make it more useful (using Span type directly from your code requires C# 7.2)." + NOTE: Deserializers are expected not to call this method (or other payload accessor methods) more than once per received message + (as there is no practical reason for doing so) and DeserializationContext implementations are free to assume so. + + read only sequence containing the entire payload. + + + + A stream of messages to be read. + Messages can be awaited await reader.MoveNext(), that returns true + if there is a message available and false if there are no more messages + (i.e. the stream has been closed). + + On the client side, the last invocation of MoveNext() either returns false + if the call has finished successfully or throws RpcException if call finished + with an error. Once the call finishes, subsequent invocations of MoveNext() will + continue yielding the same result (returning false or throwing an exception). + + + On the server side, MoveNext() does not throw exceptions. + In case of a failure, the request stream will appear to be finished + (MoveNext will return false) and the CancellationToken + associated with the call will be cancelled to signal the failure. + + + MoveNext() operations can be cancelled via a cancellation token. Cancelling + an individual read operation has the same effect as cancelling the entire call + (which will also result in the read operation returning prematurely), but the per-read cancellation + tokens passed to MoveNext() only result in cancelling the call if the read operation haven't finished + yet. + + + The message type. + + + + Gets the current element in the iteration. + + + + + Advances the reader to the next element in the sequence, returning the result asynchronously. + + Cancellation token that can be used to cancel the operation. + + Task containing the result of the operation: true if the reader was successfully advanced + to the next element; false if the reader has passed the end of the sequence. + + + + A writable stream of messages. + + The message type. + + + + Writes a message asynchronously. Only one write can be pending at a time. + + The message to be written. Cannot be null. + + + + Write options that will be used for the next write. + If null, default options will be used. + Once set, this property maintains its value across subsequent + writes. + + + + + Client-side writable stream of messages with Close capability. + + The message type. + + + + Completes/closes the stream. Can only be called once there is no pending write. No writes should follow calling this. + + + + + Extends the CallInvoker class to provide the interceptor facility on the client side. + + + + + Returns a instance that intercepts + the invoker with the given interceptor. + + The underlying invoker to intercept. + The interceptor to intercept calls to the invoker with. + + Multiple interceptors can be added on top of each other by calling + "invoker.Intercept(a, b, c)". The order of invocation will be "a", "b", and then "c". + Interceptors can be later added to an existing intercepted CallInvoker, effectively + building a chain like "invoker.Intercept(c).Intercept(b).Intercept(a)". Note that + in this case, the last interceptor added will be the first to take control. + + + + + Returns a instance that intercepts + the invoker with the given interceptors. + + The channel to intercept. + + An array of interceptors to intercept the calls to the invoker with. + Control is passed to the interceptors in the order specified. + + + Multiple interceptors can be added on top of each other by calling + "invoker.Intercept(a, b, c)". The order of invocation will be "a", "b", and then "c". + Interceptors can be later added to an existing intercepted CallInvoker, effectively + building a chain like "invoker.Intercept(c).Intercept(b).Intercept(a)". Note that + in this case, the last interceptor added will be the first to take control. + + + + + Returns a instance that intercepts + the invoker with the given interceptor. + + The underlying invoker to intercept. + + An interceptor delegate that takes the request metadata to be sent with an outgoing call + and returns a instance that will replace the existing + invocation metadata. + + + Multiple interceptors can be added on top of each other by + building a chain like "invoker.Intercept(c).Intercept(b).Intercept(a)". Note that + in this case, the last interceptor added will be the first to take control. + + + + + Creates a new instance of MetadataInterceptor given the specified interceptor function. + + + + + Provides extension methods to make it easy to register interceptors on Channel objects. + + + + + Returns a instance that intercepts + the channel with the given interceptor. + + The channel to intercept. + The interceptor to intercept the channel with. + + Multiple interceptors can be added on top of each other by calling + "channel.Intercept(a, b, c)". The order of invocation will be "a", "b", and then "c". + Interceptors can be later added to an existing intercepted channel, effectively + building a chain like "channel.Intercept(c).Intercept(b).Intercept(a)". Note that + in this case, the last interceptor added will be the first to take control. + + + + + Returns a instance that intercepts + the channel with the given interceptors. + + The channel to intercept. + + An array of interceptors to intercept the channel with. + Control is passed to the interceptors in the order specified. + + + Multiple interceptors can be added on top of each other by calling + "channel.Intercept(a, b, c)". The order of invocation will be "a", "b", and then "c". + Interceptors can be later added to an existing intercepted channel, effectively + building a chain like "channel.Intercept(c).Intercept(b).Intercept(a)". Note that + in this case, the last interceptor added will be the first to take control. + + + + + Returns a instance that intercepts + the invoker with the given interceptor. + + The channel to intercept. + + An interceptor delegate that takes the request metadata to be sent with an outgoing call + and returns a instance that will replace the existing + invocation metadata. + + + Multiple interceptors can be added on top of each other by + building a chain like "channel.Intercept(c).Intercept(b).Intercept(a)". Note that + in this case, the last interceptor added will be the first to take control. + + + + + Carries along the context associated with intercepted invocations on the client side. + + + + + Creates a new instance of + with the specified method, host, and call options. + + A object representing the method to be invoked. + The host to dispatch the current call to. + A instance containing the call options of the current call. + + + + Gets the instance + representing the method to be invoked. + + + + + Gets the host that the currect invocation will be dispatched to. + + + + + Gets the structure representing the + call options associated with the current invocation. + + + + + Decorates an underlying to + intercept calls through a given interceptor. + + + + + Creates a new instance of + with the given underlying invoker and interceptor instances. + + + + + Intercepts a simple blocking call with the registered interceptor. + + + + + Intercepts a simple asynchronous call with the registered interceptor. + + + + + Intercepts an asynchronous server streaming call with the registered interceptor. + + + + + Intercepts an asynchronous client streaming call with the registered interceptor. + + + + + Intercepts an asynchronous duplex streaming call with the registered interceptor. + + + + + Serves as the base class for gRPC interceptors. + + + + + Represents a continuation for intercepting simple blocking invocations. + A delegate of this type is passed to the BlockingUnaryCall method + when an outgoing invocation is being intercepted and calling the + delegate will invoke the next interceptor in the chain, or the underlying + call invoker if called from the last interceptor. The interceptor is + allowed to call it zero, one, or multiple times, passing it the appropriate + context and request values as it sees fit. + + Request message type for this invocation. + Response message type for this invocation. + The request value to continue the invocation with. + + The + instance to pass to the next step in the invocation process. + + + The response value of the invocation to return to the caller. + The interceptor can choose to return the return value of the + continuation delegate or an arbitrary value as it sees fit. + + + + + Represents a continuation for intercepting simple asynchronous invocations. + A delegate of this type is passed to the AsyncUnaryCall method + when an outgoing invocation is being intercepted and calling the + delegate will invoke the next interceptor in the chain, or the underlying + call invoker if called from the last interceptor. The interceptor is + allowed to call it zero, one, or multiple times, passing it the appropriate + request value and context as it sees fit. + + Request message type for this invocation. + Response message type for this invocation. + The request value to continue the invocation with. + + The + instance to pass to the next step in the invocation process. + + + An instance of + representing an asynchronous invocation of a unary RPC. + The interceptor can choose to return the same object returned from + the continuation delegate or an arbitrarily constructed instance as it sees fit. + + + + + Represents a continuation for intercepting asynchronous server-streaming invocations. + A delegate of this type is passed to the AsyncServerStreamingCall method + when an outgoing invocation is being intercepted and calling the + delegate will invoke the next interceptor in the chain, or the underlying + call invoker if called from the last interceptor. The interceptor is + allowed to call it zero, one, or multiple times, passing it the appropriate + request value and context as it sees fit. + + Request message type for this invocation. + Response message type for this invocation. + The request value to continue the invocation with. + + The + instance to pass to the next step in the invocation process. + + + An instance of + representing an asynchronous invocation of a server-streaming RPC. + The interceptor can choose to return the same object returned from + the continuation delegate or an arbitrarily constructed instance as it sees fit. + + + + + Represents a continuation for intercepting asynchronous client-streaming invocations. + A delegate of this type is passed to the AsyncClientStreamingCall method + when an outgoing invocation is being intercepted and calling the + delegate will invoke the next interceptor in the chain, or the underlying + call invoker if called from the last interceptor. The interceptor is + allowed to call it zero, one, or multiple times, passing it the appropriate + request value and context as it sees fit. + + Request message type for this invocation. + Response message type for this invocation. + + The + instance to pass to the next step in the invocation process. + + + An instance of + representing an asynchronous invocation of a client-streaming RPC. + The interceptor can choose to return the same object returned from + the continuation delegate or an arbitrarily constructed instance as it sees fit. + + + + + Represents a continuation for intercepting asynchronous duplex invocations. + A delegate of this type is passed to the AsyncDuplexStreamingCall method + when an outgoing invocation is being intercepted and calling the + delegate will invoke the next interceptor in the chain, or the underlying + call invoker if called from the last interceptor. The interceptor is + allowed to call it zero, one, or multiple times, passing it the appropriate + request value and context as it sees fit. + + + The + instance to pass to the next step in the invocation process. + + + An instance of + representing an asynchronous invocation of a duplex-streaming RPC. + The interceptor can choose to return the same object returned from + the continuation delegate or an arbitrarily constructed instance as it sees fit. + + + + + Intercepts a blocking invocation of a simple remote call. + + The request message of the invocation. + + The + associated with the current invocation. + + + The callback that continues the invocation process. + This can be invoked zero or more times by the interceptor. + The interceptor can invoke the continuation passing the given + request value and context arguments, or substitute them as it sees fit. + + + The response message of the current invocation. + The interceptor can simply return the return value of the + continuation delegate passed to it intact, or an arbitrary + value as it sees fit. + + + + + Intercepts an asynchronous invocation of a simple remote call. + + The request message of the invocation. + + The + associated with the current invocation. + + + The callback that continues the invocation process. + This can be invoked zero or more times by the interceptor. + The interceptor can invoke the continuation passing the given + request value and context arguments, or substitute them as it sees fit. + + + An instance of + representing an asynchronous unary invocation. + The interceptor can simply return the return value of the + continuation delegate passed to it intact, or construct its + own substitute as it sees fit. + + + + + Intercepts an asynchronous invocation of a streaming remote call. + + The request message of the invocation. + + The + associated with the current invocation. + + + The callback that continues the invocation process. + This can be invoked zero or more times by the interceptor. + The interceptor can invoke the continuation passing the given + request value and context arguments, or substitute them as it sees fit. + + + An instance of + representing an asynchronous server-streaming invocation. + The interceptor can simply return the return value of the + continuation delegate passed to it intact, or construct its + own substitute as it sees fit. + + + + + Intercepts an asynchronous invocation of a client streaming call. + + + The + associated with the current invocation. + + + The callback that continues the invocation process. + This can be invoked zero or more times by the interceptor. + The interceptor can invoke the continuation passing the given + context argument, or substitute as it sees fit. + + + An instance of + representing an asynchronous client-streaming invocation. + The interceptor can simply return the return value of the + continuation delegate passed to it intact, or construct its + own substitute as it sees fit. + + + + + Intercepts an asynchronous invocation of a duplex streaming call. + + + The + associated with the current invocation. + + + The callback that continues the invocation process. + This can be invoked zero or more times by the interceptor. + The interceptor can invoke the continuation passing the given + context argument, or substitute as it sees fit. + + + An instance of + representing an asynchronous duplex-streaming invocation. + The interceptor can simply return the return value of the + continuation delegate passed to it intact, or construct its + own substitute as it sees fit. + + + + + Server-side handler for intercepting and incoming unary call. + + Request message type for this method. + Response message type for this method. + The request value of the incoming invocation. + + An instance of representing + the context of the invocation. + + + A delegate that asynchronously proceeds with the invocation, calling + the next interceptor in the chain, or the service request handler, + in case of the last interceptor and return the response value of + the RPC. The interceptor can choose to call it zero or more times + at its discretion. + + + A future representing the response value of the RPC. The interceptor + can simply return the return value from the continuation intact, + or an arbitrary response value as it sees fit. + + + + + Server-side handler for intercepting client streaming call. + + Request message type for this method. + Response message type for this method. + The request stream of the incoming invocation. + + An instance of representing + the context of the invocation. + + + A delegate that asynchronously proceeds with the invocation, calling + the next interceptor in the chain, or the service request handler, + in case of the last interceptor and return the response value of + the RPC. The interceptor can choose to call it zero or more times + at its discretion. + + + A future representing the response value of the RPC. The interceptor + can simply return the return value from the continuation intact, + or an arbitrary response value as it sees fit. The interceptor has + the ability to wrap or substitute the request stream when calling + the continuation. + + + + + Server-side handler for intercepting server streaming call. + + Request message type for this method. + Response message type for this method. + The request value of the incoming invocation. + The response stream of the incoming invocation. + + An instance of representing + the context of the invocation. + + + A delegate that asynchronously proceeds with the invocation, calling + the next interceptor in the chain, or the service request handler, + in case of the last interceptor and the interceptor can choose to + call it zero or more times at its discretion. The interceptor has + the ability to wrap or substitute the request value and the response stream + when calling the continuation. + + + + + Server-side handler for intercepting bidirectional streaming calls. + + Request message type for this method. + Response message type for this method. + The request stream of the incoming invocation. + The response stream of the incoming invocation. + + An instance of representing + the context of the invocation. + + + A delegate that asynchronously proceeds with the invocation, calling + the next interceptor in the chain, or the service request handler, + in case of the last interceptor and the interceptor can choose to + call it zero or more times at its discretion. The interceptor has + the ability to wrap or substitute the request and response streams + when calling the continuation. + + + + + A writable stream of messages that is used in server-side handlers. + + + + + Key certificate pair (in PEM encoding). + + + + + Creates a new certificate chain - private key pair. + + PEM encoded certificate chain. + PEM encoded private key. + + + + PEM encoded certificate chain. + + + + + PEM encoded private key. + + + + + Encapsulates the logic for serializing and deserializing messages. + + + + + Initializes a new marshaller from simple serialize/deserialize functions. + + Function that will be used to serialize messages. + Function that will be used to deserialize messages. + + + + Initializes a new marshaller from serialize/deserialize fuctions that can access serialization and deserialization + context. Compared to the simple serializer/deserializer functions, using the contextual version provides more + flexibility and can lead to increased efficiency (and better performance). + Note: This constructor is part of an experimental API that can change or be removed without any prior notice. + + Function that will be used to serialize messages. + Function that will be used to deserialize messages. + + + + Gets the serializer function. + + + + + Gets the deserializer function. + + + + + Gets the serializer function. + Note: experimental API that can change or be removed without any prior notice. + + + + + Gets the serializer function. + Note: experimental API that can change or be removed without any prior notice. + + + + + Utilities for creating marshallers. + + + + + Creates a marshaller from specified serializer and deserializer. + + + + + Creates a marshaller from specified contextual serializer and deserializer. + Note: This method is part of an experimental API that can change or be removed without any prior notice. + + + + + Returns a marshaller for string type. This is useful for testing. + + + + + A collection of metadata entries that can be exchanged during a call. + gRPC supports these types of metadata: + + Request headersare sent by the client at the beginning of a remote call before any request messages are sent. + Response headersare sent by the server at the beginning of a remote call handler before any response messages are sent. + Response trailersare sent by the server at the end of a remote call along with resulting call status. + + + + + + All binary headers should have this suffix. + + + + + An read-only instance of metadata containing no entries. + + + + + To be used in initial metadata to request specific compression algorithm + for given call. Direct selection of compression algorithms is an internal + feature and is not part of public API. + + + + + Initializes a new instance of Metadata. + + + + + Makes this object read-only. + + this object + + + + Gets the last metadata entry with the specified key. + If there are no matching entries then null is returned. + + + + + Gets the string value of the last metadata entry with the specified key. + If the metadata entry is binary then an exception is thrown. + If there are no matching entries then null is returned. + + + + + Gets the bytes value of the last metadata entry with the specified key. + If the metadata entry is not binary the string value will be returned as ASCII encoded bytes. + If there are no matching entries then null is returned. + + + + + Gets all metadata entries with the specified key. + + + + + Adds a new ASCII-valued metadata entry. See Metadata.Entry constructor for params. + + + + + Adds a new binary-valued metadata entry. See Metadata.Entry constructor for params. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Metadata entry + + + + + Initializes a new instance of the struct with a binary value. + + Metadata key. Gets converted to lowercase. Needs to have suffix indicating a binary valued metadata entry. Can only contain lowercase alphanumeric characters, underscores, hyphens and dots. + Value bytes. + + + + Initializes a new instance of the struct with an ASCII value. + + Metadata key. Gets converted to lowercase. Must not use suffix indicating a binary valued metadata entry. Can only contain lowercase alphanumeric characters, underscores, hyphens and dots. + Value string. Only ASCII characters are allowed. + + + + Gets the metadata entry key. + + + + + Gets the binary value of this metadata entry. + If the metadata entry is not binary the string value will be returned as ASCII encoded bytes. + + + + + Gets the string value of this metadata entry. + If the metadata entry is binary then an exception is thrown. + + + + + Returns true if this entry is a binary-value entry. + + + + + Returns a that represents the current . + + + + + Gets the serialized value for this entry. For binary metadata entries, this leaks + the internal valueBytes byte array and caller must not change contents of it. + + + + + Creates a binary value or ascii value metadata entry from data received from the native layer. + We trust C core to give us well-formed data, so we don't perform any checks or defensive copying. + + + + + Returns true if the key has "-bin" binary header suffix. + + + + + Method types supported by gRPC. + + + + Single request sent from client, single response received from server. + + + Stream of request sent from client, single response received from server. + + + Single request sent from client, stream of responses received from server. + + + Both server and client can stream arbitrary number of requests and responses simultaneously. + + + + A non-generic representation of a remote method. + + + + + Gets the type of the method. + + + + + Gets the name of the service to which this method belongs. + + + + + Gets the unqualified name of the method. + + + + + Gets the fully qualified name of the method. On the server side, methods are dispatched + based on this name. + + + + + A description of a remote method. + + Request message type for this method. + Response message type for this method. + + + + Initializes a new instance of the Method class. + + Type of method. + Name of service this method belongs to. + Unqualified name of the method. + Marshaller used for request messages. + Marshaller used for response messages. + + + + Gets the type of the method. + + + + + Gets the name of the service to which this method belongs. + + + + + Gets the unqualified name of the method. + + + + + Gets the marshaller used for request messages. + + + + + Gets the marshaller used for response messages. + + + + + Gets the fully qualified name of the method. On the server side, methods are dispatched + based on this name. + + + + + Gets full name of the method including the service name. + + + + + Thrown when remote procedure call fails. Every RpcException is associated with a resulting of the call. + + + + + Creates a new RpcException associated with given status. + + Resulting status of a call. + + + + Creates a new RpcException associated with given status and message. + NOTE: the exception message is not sent to the remote peer. Use status.Details to pass error + details to the peer. + + Resulting status of a call. + The exception message. + + + + Creates a new RpcException associated with given status and trailing response metadata. + + Resulting status of a call. + Response trailing metadata. + + + + Creates a new RpcException associated with given status, message and trailing response metadata. + NOTE: the exception message is not sent to the remote peer. Use status.Details to pass error + details to the peer. + + Resulting status of a call. + Response trailing metadata. + The exception message. + + + + Resulting status of the call. + + + + + Returns the status code of the call, as a convenient alternative to Status.StatusCode. + + + + + Gets the call trailing metadata. + Trailers only have meaningful content for client-side calls (in which case they represent the trailing metadata sent by the server when closing the call). + Instances of RpcException thrown by the server-side part of the stack will have trailers always set to empty. + + + + + Provides storage for payload when serializing a message. + + + + + Use the byte array as serialized form of current message and mark serialization process as complete. + Complete(byte[]) can only be called once. By calling this method the caller gives up the ownership of the + payload which must not be accessed afterwards. + + the serialized form of current message + + + + Gets buffer writer that can be used to write the serialized data. Once serialization is finished, + Complete() needs to be called. + + + + + Sets the payload length when writing serialized data into a buffer writer. If the serializer knows the full payload + length in advance, providing that information before obtaining the buffer writer using GetBufferWriter() can improve + serialization efficiency by avoiding copies. The provided payload length must be the same as the data written to the writer. + Calling this method is optional. If the payload length is not set then the length is calculated using the data written to + the buffer writer when Complete() is called. + + The total length of the payload in bytes. + + + + Complete the payload written to the buffer writer. Complete() can only be called once. + + + + + Context for a server-side call. + + + + + Creates a new instance of ServerCallContext. + + + + + Asynchronously sends response headers for the current call to the client. This method may only be invoked once for each call and needs to be invoked + before any response messages are written. Writing the first response message implicitly sends empty response headers if WriteResponseHeadersAsync haven't + been called yet. + + The response headers to send. + The task that finished once response headers have been written. + + + + Creates a propagation token to be used to propagate call context to a child call. + + + + Name of method called in this RPC. + + + Name of host called in this RPC. + + + Address of the remote endpoint in URI format. + + + Deadline for this RPC. The call will be automatically cancelled once the deadline is exceeded. + + + Initial metadata sent by client. + + + Cancellation token signals when call is cancelled. It is also triggered when the deadline is exceeeded or there was some other error (e.g. network problem). + + + Trailers to send back to client after RPC finishes. + + + Status to send back to client after RPC finishes. + + + + Allows setting write options for the following write. + For streaming response calls, this property is also exposed as on IServerStreamWriter for convenience. + Both properties are backed by the same underlying value. + + + + + Gets the AuthContext associated with this call. + Note: Access to AuthContext is an experimental API that can change without any prior notice. + + + + + Gets a dictionary that can be used by the various interceptors and handlers of this + call to store arbitrary state. + + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + Provides implementation of a non-virtual public member. + + + + Server-side handler for unary call. + + Request message type for this method. + Response message type for this method. + + + + Server-side handler for client streaming call. + + Request message type for this method. + Response message type for this method. + + + + Server-side handler for server streaming call. + + Request message type for this method. + Response message type for this method. + + + + Server-side handler for bidi streaming call. + + Request message type for this method. + Response message type for this method. + + + + Stores mapping of methods to server call handlers. + Normally, the ServerServiceDefinition objects will be created by the BindService factory method + that is part of the autogenerated code for a protocol buffers service definition. + + + + + Forwards all the previously stored AddMethod calls to the service binder. + + + + + Creates a new builder object for ServerServiceDefinition. + + The builder object. + + + + Builder class for . + + + + + Creates a new instance of builder. + + + + + Adds a definition for a single request - single response method. + + The request message class. + The response message class. + The method. + The method handler. + This builder instance. + + + + Adds a definition for a client streaming method. + + The request message class. + The response message class. + The method. + The method handler. + This builder instance. + + + + Adds a definition for a server streaming method. + + The request message class. + The response message class. + The method. + The method handler. + This builder instance. + + + + Adds a definition for a bidirectional streaming method. + + The request message class. + The response message class. + The method. + The method handler. + This builder instance. + + + + Creates an immutable ServerServiceDefinition from this builder. + + The ServerServiceDefinition object. + + + + Allows binding server-side method implementations in alternative serving stacks. + Instances of this class are usually populated by the BindService method + that is part of the autogenerated code for a protocol buffers service definition. + + + + + Adds a definition for a single request - single response method. + + The request message class. + The response message class. + The method. + The method handler. + + + + Adds a definition for a client streaming method. + + The request message class. + The response message class. + The method. + The method handler. + + + + Adds a definition for a server streaming method. + + The request message class. + The response message class. + The method. + The method handler. + + + + Adds a definition for a bidirectional streaming method. + + The request message class. + The response message class. + The method. + The method handler. + + + + Callback invoked with the expected targetHost and the peer's certificate. + If false is returned by this callback then it is treated as a + verification failure and the attempted connection will fail. + Invocation of the callback is blocking, so any + implementation should be light-weight. + Note that the callback can potentially be invoked multiple times, + concurrently from different threads (e.g. when multiple connections + are being created for the same credentials). + + The associated with the callback + true if verification succeeded, false otherwise. + Note: experimental API that can change or be removed without any prior notice. + + + + Client-side SSL credentials. + + + + + Creates client-side SSL credentials loaded from + disk file pointed to by the GRPC_DEFAULT_SSL_ROOTS_FILE_PATH environment variable. + If that fails, gets the roots certificates from a well known place on disk. + + + + + Creates client-side SSL credentials from + a string containing PEM encoded root certificates. + + + + + Creates client-side SSL credentials. + + string containing PEM encoded server root certificates. + a key certificate pair. + + + + Creates client-side SSL credentials. + + string containing PEM encoded server root certificates. + a key certificate pair. + a callback to verify peer's target name and certificate. + Note: experimental API that can change or be removed without any prior notice. + + + + PEM encoding of the server root certificates. + + + + + Client side key and certificate pair. + If null, client will not use key and certificate pair. + + + + + Populates channel credentials configurator with this instance's configuration. + End users never need to invoke this method as it is part of internal implementation. + + + + + Represents RPC result, which consists of and an optional detail string. + + + + + Default result of a successful RPC. StatusCode=OK, empty details message. + + + + + Default result of a cancelled RPC. StatusCode=Cancelled, empty details message. + + + + + Creates a new instance of Status. + + Status code. + Detail. + + + + Creates a new instance of Status. + Users should not use this constructor, except for creating instances for testing. + The debug error string should only be populated by gRPC internals. + Note: experimental API that can change or be removed without any prior notice. + + Status code. + Detail. + Optional internal error details. + + + + Gets the gRPC status code. OK indicates success, all other values indicate an error. + + + + + Gets the detail. + + + + + In case of an error, this field may contain additional error details to help with debugging. + This field will be only populated on a client and its value is generated locally, + based on the internal state of the gRPC client stack (i.e. the value is never sent over the wire). + Note that this field is available only for debugging purposes, the application logic should + never rely on values of this field (it should use StatusCode and Detail instead). + Example: when a client fails to connect to a server, this field may provide additional details + why the connection to the server has failed. + Note: experimental API that can change or be removed without any prior notice. + + + + + Returns a that represents the current . + + + + + Result of a remote procedure call. + Based on grpc_status_code from grpc/status.h + + + + Not an error; returned on success. + + + The operation was cancelled (typically by the caller). + + + + Unknown error. An example of where this error may be returned is + if a Status value received from another address space belongs to + an error-space that is not known in this address space. Also + errors raised by APIs that do not return enough error information + may be converted to this error. + + + + + Client specified an invalid argument. Note that this differs + from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments + that are problematic regardless of the state of the system + (e.g., a malformed file name). + + + + + Deadline expired before operation could complete. For operations + that change the state of the system, this error may be returned + even if the operation has completed successfully. For example, a + successful response from a server could have been delayed long + enough for the deadline to expire. + + + + Some requested entity (e.g., file or directory) was not found. + + + Some entity that we attempted to create (e.g., file or directory) already exists. + + + + The caller does not have permission to execute the specified + operation. PERMISSION_DENIED must not be used for rejections + caused by exhausting some resource (use RESOURCE_EXHAUSTED + instead for those errors). PERMISSION_DENIED must not be + used if the caller can not be identified (use UNAUTHENTICATED + instead for those errors). + + + + The request does not have valid authentication credentials for the operation. + + + + Some resource has been exhausted, perhaps a per-user quota, or + perhaps the entire file system is out of space. + + + + + Operation was rejected because the system is not in a state + required for the operation's execution. For example, directory + to be deleted may be non-empty, an rmdir operation is applied to + a non-directory, etc. + + + + + The operation was aborted, typically due to a concurrency issue + like sequencer check failures, transaction aborts, etc. + + + + + Operation was attempted past the valid range. E.g., seeking or + reading past end of file. + + + + Operation is not implemented or not supported/enabled in this service. + + + + Internal errors. Means some invariants expected by underlying + system has been broken. If you see one of these errors, + something is very broken. + + + + + The service is currently unavailable. This is a most likely a + transient condition and may be corrected by retrying with + a backoff. Note that it is not always safe to retry + non-idempotent operations. + + + + Unrecoverable data loss or corruption. + + + + Converts byte* pointing to an encoded byte array to a string using the provided Encoding. + + + + + Converts IntPtr pointing to a encoded byte array to a string using the provided Encoding. + + + + + Utility methods to simplify checking preconditions in the code. + + + + + Throws if condition is false. + + The condition. + + + + Throws with given message if condition is false. + + The condition. + The error message. + + + + Throws if reference is null. + + The reference. + + + + Throws if reference is null. + + The reference. + The parameter name. + + + + Throws if condition is false. + + The condition. + + + + Throws with given message if condition is false. + + The condition. + The error message. + + + + Verification context for VerifyPeerCallback. + Note: experimental API that can change or be removed without any prior notice. + + + + + Initializes a new instance of the class. + + The target name of the peer. + The PEM encoded certificate of the peer. + + + + The target name of the peer. + + + + + The PEM encoded certificate of the peer. + + + + + Provides info about current version of gRPC. + See https://codingforsmarties.wordpress.com/2016/01/21/how-to-version-assemblies-destined-for-nuget/ + for rationale about assembly versioning. + + + + + Current AssemblyVersion attribute of gRPC C# assemblies + + + + + Current AssemblyFileVersion of gRPC C# assemblies + + + + + Current version of gRPC C# + + + + + Flags for write operations. + + + + + Hint that the write may be buffered and need not go out on the wire immediately. + gRPC is free to buffer the message until the next non-buffered + write, or until write stream completion, but it need not buffer completely or at all. + + + + + Force compression to be disabled for a particular write. + + + + + Options for write operations. + + + + + Default write options. + + + + + Initializes a new instance of WriteOptions class. + + The write flags. + + + + Gets the write flags. + + + + + Indicates that certain members on a specified are accessed dynamically, + for example through . + + + This allows tools to understand which members are being accessed during the execution + of a program. + + This attribute is valid on members whose type is or . + + When this attribute is applied to a location of type , the assumption is + that the string represents a fully qualified type name. + + If the attribute is applied to a method it's treated as a special case and it implies + the attribute should be applied to the "this" parameter of the method. As such the attribute + should only be used on instance methods of types assignable to System.Type (or string, but no methods + will use it there). + + + + + Initializes a new instance of the class + with the specified member types. + + The types of members dynamically accessed. + + + + Gets the which specifies the type + of members dynamically accessed. + + + + + Specifies the types of members that are dynamically accessed. + + This enumeration has a attribute that allows a + bitwise combination of its member values. + + + + + Specifies no members. + + + + + Specifies the default, parameterless public constructor. + + + + + Specifies all public constructors. + + + + + Specifies all non-public constructors. + + + + + Specifies all public methods. + + + + + Specifies all non-public methods. + + + + + Specifies all public fields. + + + + + Specifies all non-public fields. + + + + + Specifies all public nested types. + + + + + Specifies all non-public nested types. + + + + + Specifies all public properties. + + + + + Specifies all non-public properties. + + + + + Specifies all public events. + + + + + Specifies all non-public events. + + + + + Specifies all members. + + + + diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45/Grpc.Core.Api.xml.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45/Grpc.Core.Api.xml.meta new file mode 100644 index 00000000..e3814dc5 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.Api/lib/net45/Grpc.Core.Api.xml.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 0a4fb8823a783423880c9d8c9d3b5cf4 +timeCreated: 1531219386 +licenseType: Free +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.meta new file mode 100644 index 00000000..47737027 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: e28eaddc034fe664591e93e8816968aa +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib.meta new file mode 100644 index 00000000..0e284f0b --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 1f862d451f11a2442aeac99ad2827285 +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45.meta new file mode 100644 index 00000000..85acb0b2 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 89bdbe2a1282d4e40ba11e96b1481d09 +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45/Grpc.Core.dll.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45/Grpc.Core.dll.meta new file mode 100644 index 00000000..f22a7c4c --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45/Grpc.Core.dll.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: 63fdcd70d29d1dc49b4e61e22a9e96e1 +timeCreated: 1531219386 +licenseType: Free +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45/Grpc.Core.xml b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45/Grpc.Core.xml new file mode 100644 index 00000000..86aa3a59 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45/Grpc.Core.xml @@ -0,0 +1,2270 @@ + + + + Grpc.Core + + + + + Details about a client-side call to be invoked. + + Request message type for the call. + Response message type for the call. + + + + Initializes a new instance of the struct. + + Channel to use for this call. + Method to call. + Call options. + + + + Initializes a new instance of the struct. + + Channel to use for this call. + Method to call. + Host that contains the method. if null, default host will be used. + Call options. + + + + Initializes a new instance of the struct. + + Channel to use for this call. + Qualified method name. + Host that contains the method. + Request marshaller. + Response marshaller. + Call options. + + + + Get channel associated with this call. + + + + + Gets name of method to be called. + + + + + Get name of host. + + + + + Gets marshaller used to serialize requests. + + + + + Gets marshaller used to deserialized responses. + + + + + Gets the call options. + + + + + Returns new instance of with + Options set to the value provided. Values of all other fields are preserved. + + + + + Helper methods for generated clients to make RPC calls. + Most users will use this class only indirectly and will be + making calls using client object generated from protocol + buffer definition files. + + + + + Invokes a simple remote call in a blocking fashion. + + The response. + The call definition. + Request message. + Type of request message. + The of response message. + + + + Invokes a simple remote call asynchronously. + + An awaitable call object providing access to the response. + The call definition. + Request message. + Type of request message. + The of response message. + + + + Invokes a server streaming call asynchronously. + In server streaming scenario, client sends on request and server responds with a stream of responses. + + A call object providing access to the asynchronous response stream. + The call definition. + Request message. + Type of request message. + The of response messages. + + + + Invokes a client streaming call asynchronously. + In client streaming scenario, client sends a stream of requests and server responds with a single response. + + The call definition. + An awaitable call object providing access to the response. + Type of request messages. + The of response message. + + + + Invokes a duplex streaming call asynchronously. + In duplex streaming scenario, client sends a stream of requests and server responds with a stream of responses. + The response stream is completely independent and both side can be sending messages at the same time. + + A call object providing access to the asynchronous request and response streams. + The call definition. + Type of request messages. + Type of responsemessages. + + + + Represents a gRPC channel. Channels are an abstraction of long-lived connections to remote servers. + More client objects can reuse the same channel. Creating a channel is an expensive operation compared to invoking + a remote call so in general you should reuse a single channel for as many calls as possible. + + + + + Creates a channel that connects to a specific host. + Port will default to 80 for an unsecure channel and to 443 for a secure channel. + + Target of the channel. + Credentials to secure the channel. + + + + Creates a channel that connects to a specific host. + Port will default to 80 for an unsecure channel or to 443 for a secure channel. + + Target of the channel. + Credentials to secure the channel. + Channel options. + + + + Creates a channel that connects to a specific host and port. + + The name or IP address of the host. + The port. + Credentials to secure the channel. + + + + Creates a channel that connects to a specific host and port. + + The name or IP address of the host. + The port. + Credentials to secure the channel. + Channel options. + + + + Gets current connectivity state of this channel. + After channel has been shutdown, ChannelState.Shutdown will be returned. + + + + + Returned tasks completes once channel state has become different from + given lastObservedState. + If deadline is reached or an error occurs, returned task is cancelled. + + + + + Returned tasks completes once channel state has become different from + given lastObservedState (true is returned) or if the wait has timed out (false is returned). + + + + Resolved address of the remote endpoint in URI format. + + + + Returns a token that gets cancelled once ShutdownAsync is invoked. + + + + + Allows explicitly requesting channel to connect without starting an RPC. + Returned task completes once state Ready was seen. If the deadline is reached, + or channel enters the Shutdown state, the task is cancelled. + There is no need to call this explicitly unless your use case requires that. + Starting an RPC on a new channel will request connection implicitly. + + The deadline. null indicates no deadline. + + + Provides implementation of a non-virtual public member. + + + + Create a new for the channel. + + A new . + + + + Channel option specified when creating a channel. + Corresponds to grpc_channel_args from grpc/grpc.h. + Commonly used channel option names are defined in ChannelOptions, + but any of the GRPC_ARG_* channel options names defined in grpc_types.h can be used. + + + + + Type of ChannelOption. + + + + + Channel option with integer value. + + + + + Channel option with string value. + + + + + Creates a channel option with a string value. + + Name. + String value. + + + + Creates a channel option with an integer value. + + Name. + Integer value. + + + + Gets the type of the ChannelOption. + + + + + Gets the name of the ChannelOption. + + + + + Gets the integer value the ChannelOption. + + + + + Gets the string value the ChannelOption. + + + + + Determines whether the specified object is equal to the current object. + + + + + Determines whether the specified object is equal to the current object. + + + + + A hash code for the current object. + + + + + Equality operator. + + + + + Inequality operator. + + + + + Defines names of most commonly used channel options. + Other supported options names can be found in grpc_types.h (GRPC_ARG_* definitions) + + + + Override SSL target check. Only to be used for testing. + + + Enable census for tracing and stats collection + + + Maximum number of concurrent incoming streams to allow on a http2 connection + + + Maximum message length that the channel can receive + + + Maximum message length that the channel can send + + + Obsolete, for backward compatibility only. + + + Initial sequence number for http2 transports + + + Default authority for calls. + + + Primary user agent: goes at the start of the user-agent metadata + + + Secondary user agent: goes at the end of the user-agent metadata + + + If non-zero, allow the use of SO_REUSEPORT for server if it's available (default 1) + + + + Creates native object for a collection of channel options. + + The native channel arguments. + + + + Connectivity state of a channel. + Based on grpc_connectivity_state from grpc/grpc.h + + + + + Channel is idle + + + + + Channel is connecting + + + + + Channel is ready for work + + + + + Channel has seen a failure but expects to recover + + + + + Channel has seen a failure that it cannot recover from + + + + + Compression level based on grpc_compression_level from grpc/compression.h + + + + + No compression. + + + + + Low compression. + + + + + Medium compression. + + + + + High compression. + + + + + Invokes client RPCs using . + + + + + Initializes a new instance of the class. + + Channel to use. + + + + Invokes a simple remote call in a blocking fashion. + + + + + Invokes a simple remote call asynchronously. + + + + + Invokes a server streaming call asynchronously. + In server streaming scenario, client sends on request and server responds with a stream of responses. + + + + + Invokes a client streaming call asynchronously. + In client streaming scenario, client sends a stream of requests and server responds with a single response. + + + + + Invokes a duplex streaming call asynchronously. + In duplex streaming scenario, client sends a stream of requests and server responds with a stream of responses. + The response stream is completely independent and both side can be sending messages at the same time. + + + + Creates call invocation details for given method. + + + + Encapsulates initialization and shutdown of gRPC library. + + + + + Returns a reference-counted instance of initialized gRPC environment. + Subsequent invocations return the same instance unless reference count has dropped to zero previously. + + + + + Decrements the reference count for currently active environment and asynchronously shuts down the gRPC environment if reference count drops to zero. + + + + + Requests shutdown of all channels created by the current process. + + + + + Requests immediate shutdown of all servers created by the current process. + + + + + Gets application-wide logger used by gRPC. + + The logger. + + + + Sets the application-wide logger that should be used by gRPC. + + + + + Sets the number of threads in the gRPC thread pool that polls for internal RPC events. + Can be only invoked before the GrpcEnviroment is started and cannot be changed afterwards. + Setting thread pool size is an advanced setting and you should only use it if you know what you are doing. + Most users should rely on the default value provided by gRPC library. + Note: this method is part of an experimental API that can change or be removed without any prior notice. + + + + + Sets the number of completion queues in the gRPC thread pool that polls for internal RPC events. + Can be only invoked before the GrpcEnviroment is started and cannot be changed afterwards. + Setting the number of completions queues is an advanced setting and you should only use it if you know what you are doing. + Most users should rely on the default value provided by gRPC library. + Note: this method is part of an experimental API that can change or be removed without any prior notice. + + + + + By default, gRPC's internal event handlers get offloaded to .NET default thread pool thread (inlineHandlers=false). + Setting inlineHandlers to true will allow scheduling the event handlers directly to + GrpcThreadPool internal threads. That can lead to significant performance gains in some situations, + but requires user to never block in async code (incorrectly written code can easily lead to deadlocks). + Inlining handlers is an advanced setting and you should only use it if you know what you are doing. + Most users should rely on the default value provided by gRPC library. + Note: this method is part of an experimental API that can change or be removed without any prior notice. + Note: inlineHandlers=true was the default in gRPC C# v1.4.x and earlier. + + + + + Sets the parameters for a pool that caches batch context instances. Reusing batch context instances + instead of creating a new one for every C core operation helps reducing the GC pressure. + Can be only invoked before the GrpcEnviroment is started and cannot be changed afterwards. + This is an advanced setting and you should only use it if you know what you are doing. + Most users should rely on the default value provided by gRPC library. + Note: this method is part of an experimental API that can change or be removed without any prior notice. + + + + + Sets the parameters for a pool that caches request call context instances. Reusing request call context instances + instead of creating a new one for every requested call in C core helps reducing the GC pressure. + Can be only invoked before the GrpcEnviroment is started and cannot be changed afterwards. + This is an advanced setting and you should only use it if you know what you are doing. + Most users should rely on the default value provided by gRPC library. + Note: this method is part of an experimental API that can change or be removed without any prior notice. + + + + + Occurs when GrpcEnvironment is about the start the shutdown logic. + If GrpcEnvironment is later initialized and shutdown, the event will be fired again (unless unregistered first). + + + + + Creates gRPC environment. + + + + + Gets the completion queues used by this gRPC environment. + + + + + Picks a completion queue in a round-robin fashion. + Shouldn't be invoked on a per-call basis (used at per-channel basis). + + + + + Gets the completion queue used by this gRPC environment. + + + + + Gets version of gRPC C core. + + + + + Shuts down this environment. + + + + + Handler for AppDomain.DomainUnload, AppDomain.ProcessExit and AssemblyLoadContext.Unloading hooks. + + + + + Extends the ServerServiceDefinition class to add methods used to register interceptors on the server side. + + + + + Returns a instance that + intercepts incoming calls to the underlying service handler through the given interceptor. + + The instance to register interceptors on. + The interceptor to intercept the incoming invocations with. + + Multiple interceptors can be added on top of each other by calling + "serverServiceDefinition.Intercept(a, b, c)". The order of invocation will be "a", "b", and then "c". + Interceptors can be later added to an existing intercepted service definition, effectively + building a chain like "serverServiceDefinition.Intercept(c).Intercept(b).Intercept(a)". Note that + in this case, the last interceptor added will be the first to take control. + + + + + Returns a instance that + intercepts incoming calls to the underlying service handler through the given interceptors. + + The instance to register interceptors on. + + An array of interceptors to intercept the incoming invocations with. + Control is passed to the interceptors in the order specified. + + + Multiple interceptors can be added on top of each other by calling + "serverServiceDefinition.Intercept(a, b, c)". The order of invocation will be "a", "b", and then "c". + Interceptors can be later added to an existing intercepted service definition, effectively + building a chain like "serverServiceDefinition.Intercept(c).Intercept(b).Intercept(a)". Note that + in this case, the last interceptor added will be the first to take control. + + + + + Helper for creating ServerServiceDefinition with intercepted handlers. + + + + + Manages client side native call lifecycle. + + + + + This constructor should only be used for testing. + + + + + Blocking unary request - unary response call. + + + + + Starts a unary request - unary response call. + + + + + Starts a streamed request - unary response call. + Use StartSendMessage and StartSendCloseFromClient to stream requests. + + + + + Starts a unary request - streamed response call. + + + + + Starts a streaming request - streaming response call. + Use StartSendMessage and StartSendCloseFromClient to stream requests. + + + + + Sends a streaming request. Only one pending send action is allowed at any given time. + + + + + Receives a streaming response. Only one pending read action is allowed at any given time. + + + + + Sends halfclose, indicating client is done with streaming requests. + Only one pending send action is allowed at any given time. + + + + + Get the task that completes once if streaming response call finishes with ok status and throws RpcException with given status otherwise. + + + + + Get the task that completes once response headers are received. + + + + + Gets the resulting status if the call has already finished. + Throws InvalidOperationException otherwise. + + + + + Gets the trailing metadata if the call has already finished. + Throws InvalidOperationException otherwise. + + + + + Gets WriteFlags set in callDetails.Options.WriteOptions + + + + + Handles receive status completion for calls with streaming response. + + + + + Handler for unary response completion. + + + + + Handles receive status completion for calls with streaming response. + + + + + Base for handling both client side and server side calls. + Manages native call lifecycle and provides convenience methods. + + + + + Requests cancelling the call. + + + + + Requests cancelling the call with given status. + + + + + Initiates sending a message. Only one send operation can be active at a time. + + + + + Initiates reading a message. Only one read operation can be active at a time. + + + + + If there are no more pending actions and no new actions can be started, releases + the underlying native resources. + + + + + Returns an exception to throw for a failed send operation. + It is only allowed to call this method for a call that has already finished. + + + + + Checks if sending is allowed and possibly returns a Task that allows short-circuiting the send + logic by directly returning the write operation result task. Normally, null is returned. + + + + + Handles send completion (including SendCloseFromClient). + + + + + Handles send status from server completion. + + + + + Handles streaming read completion. + + + + + Manages server side native call lifecycle. + + + + + Only for testing purposes. + + + + + Starts a server side call. + + + + + Sends a streaming response. Only one pending send action is allowed at any given time. + + + + + Receives a streaming request. Only one pending read action is allowed at any given time. + + + + + Initiates sending a initial metadata. + Even though C-core allows sending metadata in parallel to sending messages, we will treat sending metadata as a send message operation + to make things simpler. + + + + + Sends call result status, indicating we are done with writes. + Sending a status different from StatusCode.OK will also implicitly cancel the call. + + + + + Gets cancellation token that gets cancelled once close completion + is received and the cancelled flag is set. + + + + + Handles the server side close completion. + + + + + grpc_auth_context + + + + + Copies contents of the native auth context into a new AuthContext instance. + + + + + grpc_auth_property + + + + + grpc_auth_property_iterator + + + + + grpcsharp_batch_context + + + + + grpc_call_credentials from grpc/grpc_security.h + + + + + grpc_call_error from grpc/grpc.h + + + + + Checks the call API invocation's result is OK. + + + + + Returns a new instance of with + all previously unset values set to their defaults and deadline and cancellation + token propagated when appropriate. + + + + + grpc_call from grpc/grpc.h + + + + + Only for testing. + + + + + grpc_channel_args from grpc/grpc.h + + + + + grpc_channel_credentials from grpc/grpc_security.h + + + + + grpc_channel from grpc/grpc.h + + + + + Writes requests asynchronously to an underlying AsyncCall object. + + + + + Status + metadata received on client side when call finishes. + (when receive_status_on_client operation finishes). + + + + + gpr_clock_type from grpc/support/time.h + + + + + This source file is shared by both Grpc.Core and Grpc.Tools to avoid duplication + of platform detection code. + + + + + grpc_event from grpc/grpc.h + + + + + grpc_completion_type from grpc/grpc.h + + + + + grpc_completion_queue from grpc/grpc.h + + + + + Create a completion queue that can only be used for Pluck operations. + + + + + Create a completion queue that can only be used for Next operations. + + + + + Creates a new usage scope for this completion queue. Once successfully created, + the completion queue won't be shutdown before scope.Dispose() is called. + + + + + Completion registry associated with this completion queue. + Doesn't need to be set if only using Pluck() operations. + + + + + For testing purposes only. NOT threadsafe. + + + + + IntPtr doesn't implement IEquatable{IntPtr} so we need to use custom comparer to avoid boxing. + + + + + Context propagation flags from grpc/grpc.h. + + + + + Implementation of ContextPropagationToken that carries + all fields needed for context propagation by C-core based implementation of gRPC. + Instances of ContextPropagationToken that are not of this + type will be recognized as "foreign" and will be silently ignored + (treated as if null). + + + + + Default propagation mask used by C core. + + + + + Default propagation mask used by C# - we want to propagate deadline + and cancellation token by our own means, everything else will be propagated + by C core automatically (according to DefaultCoreMask). + + + + + Gets the native handle of the parent call. + + + + + Gets the parent call's deadline. + + + + + Gets the parent call's cancellation token. + + + + + Get the context propagation options. + + + + + Converts given ContextPropagationToken to ContextPropagationTokenImpl + if possible or returns null. + Being able to convert means that the context propagation token is recognized as + "ours" (was created by this implementation). + + + + + Represents error details provides by C-core's debug_error_string + + + + + Owned char* object. + + + + + Checks the debug stats and take action for any inconsistency found. + + + + + Creates native call credential objects from instances of CallCredentials. + + + + + Creates native object for the credentials. + + The native credentials. + + + + Creates native call credential objects from instances of ChannelCredentials. + + + + + Creates native object for the credentials. + + The native credentials. + + + + Pool of objects that combines a shared pool and a thread local pool. + + + + + Initializes a new instance of DefaultObjectPool with given shared capacity and thread local capacity. + Thread local capacity should be significantly smaller than the shared capacity as we don't guarantee immediately + disposing the objects in the thread local pool after this pool is disposed (they will eventually be garbage collected + after the thread that owns them has finished). + On average, the shared pool will only be accessed approx. once for every threadLocalCapacity / 2 rent or lease + operations. + + + + + Leases an item from the pool or creates a new instance if the pool is empty. + Attempts to retrieve the item from the thread local pool first. + If the thread local pool is empty, the item is taken from the shared pool + along with more items that are moved to the thread local pool to avoid + prevent acquiring the lock for shared pool too often. + The methods should not be called after the pool is disposed, but it won't + results in an error to do so (after depleting the items potentially left + in the thread local pool, it will continue returning new objects created by the factory). + + + + + Returns an item to the pool. + Attempts to add the item to the thread local pool first. + If the thread local pool is full, item is added to a shared pool, + along with half of the items for the thread local pool, which + should prevent acquiring the lock for shared pool too often. + If called after the pool is disposed, we make best effort not to + add anything to the thread local pool and we guarantee not to add + anything to the shared pool (items will be disposed instead). + + + + + Expose serializer as buffer writer + + + + + Complete the payload written so far. + + + + + Overrides the content of default SSL roots. + + + + + Overrides C core's default roots with roots.pem loaded as embedded resource. + + + + + Pool of threads polling on a set of completions queues. + + + + + Creates a thread pool threads polling on a set of completions queues. + + Environment. + Pool size. + Completion queue count. + Handler inlining. + + + + Returns true if there is at least one thread pool thread that hasn't + already stopped. + Threads can either stop because all completion queues shut down or + because all foreground threads have already shutdown and process is + going to exit. + + + + + Body of the polling thread. + + + + + Abstraction of a native call object. + + + + + Pool of objects. + + + + + An object that can be pooled in IObjectPool. + + + + + + Set the action that will be invoked to return a leased object to the pool. + + + + + Exposes non-generic members of ServerReponseStream. + + + + + Asynchronously sends response headers for the current call to the client. See ServerCallContext.WriteResponseHeadersAsync for exact semantics. + + + + + Gets or sets the write options. + + + + + Useful methods for native/managed marshalling. + + + + + Converts IntPtr pointing to a UTF-8 encoded byte array to string. + + + + + UTF-8 encodes the given string into a buffer of sufficient size + + + + + Returns the maximum number of bytes required to encode a given string. + + + + + Returns the actual number of bytes required to encode a given string. + + + + + grpc_metadata_array from grpc/grpc.h + + + + + Reads metadata from pointer to grpc_metadata_array + + + + + Use this attribute to mark methods that will be called back from P/Invoke calls. + iOS (and probably other AOT platforms) needs to have delegates registered. + Instead of depending on Xamarin.iOS for this, we can just create our own, + the iOS runtime just checks for the type name. + See: https://docs.microsoft.com/en-gb/xamarin/ios/internals/limitations#reverse-callbacks + + + + + Takes care of loading C# native extension and provides access to PInvoke calls the library exports. + + + + + Gets singleton instance of this class. + The native extension is loaded when called for the first time. + + + + + Provides access to the exported native methods. + + + + + Detects which configuration of native extension to load and explicitly loads the dynamic library. + The explicit load makes sure that we can detect any loading problems early on. + + + + + Loads native methods using the [DllImport(LIBRARY_NAME)] attributes. + Note that this way of loading the native extension is "lazy" and doesn't + detect any "missing library" problems until we actually try to invoke the native methods + (which could be too late and could cause weird hangs at startup) + + + + + Loads native extension and return native methods delegates. + + + + + Return native method delegates when running on Unity platform. + Unity does not use standard NuGet packages and the native library is treated + there as a "native plugin" which is (provided it has the right metadata) + automatically made available to [DllImport] loading logic. + WARNING: Unity support is experimental and work-in-progress. Don't expect it to work. + + + + + Return native method delegates when running on the Xamarin platform. + On Xamarin, the standard [DllImport] loading logic just works + as the native library metadata is provided by the AndroidNativeLibrary or + NativeReference items in the Xamarin projects (injected automatically + by the Grpc.Core.Xamarin nuget). + WARNING: Xamarin support is experimental and work-in-progress. Don't expect it to work. + + + + + Logs from gRPC C core library can get lost if your application is not a console app. + This class allows redirection of logs to gRPC logger. + + + + + Redirects logs from native gRPC C core library to a general logger. + + + + + Provides access to all native methods provided by NativeExtension. + An extra level of indirection is added to P/Invoke calls to allow intelligent loading + of the right configuration of the native extension based on current platform, architecture etc. + + + + + Gets singleton instance of this class. + + + + + Delegate types for all published native methods. Declared under inner class to prevent scope pollution. + + + + + grpc_csharp_ext used as a static library (e.g Unity iOS). + + + + + grpc_csharp_ext used as a shared library (e.g on Unity Standalone and Android). + + + + + grpc_csharp_ext used as a shared library (with x86 suffix) + + + + + grpc_csharp_ext used as a shared library (with x64 suffix) + + + + + grpc_csharp_ext used as a shared library (with arm64 suffix) + + + + + grpc_csharp_ext used as a shared library (with x86.dll suffix) + + + + + grpc_csharp_ext used as a shared library (with x64.dll suffix) + + + + + Utility methods for detecting platform and architecture. + + + + + true if running on Unity platform. + + + + + true if running on Unity iOS, false otherwise. + + + + + true if running on a Xamarin platform (either Xamarin.Android or Xamarin.iOS), + false otherwise. + + + + + true if running on Xamarin.iOS, false otherwise. + + + + + true if running on Xamarin.Android, false otherwise. + + + + + true if running on .NET 5+, false otherwise. + + + + + Contains RuntimeInformation.FrameworkDescription if the property is available on current TFM. + null otherwise. + + + + + Contains the version of common language runtime obtained from Environment.Version + if the property is available on current TFM. null otherwise. + + + + + true if running on .NET Core (CoreCLR) or NET 5+, false otherwise. + + + + + Returns UnityEngine.Application.platform as a string. + See https://docs.unity3d.com/ScriptReference/Application-platform.html for possible values. + Value is obtained via reflection to avoid compile-time dependency on Unity. + This method should only be called if IsUnity is true. + + + + + Returns UnityEngine.Application.platform as a string or null + if not running on Unity. + Value is obtained via reflection to avoid compile-time dependency on Unity. + + + + + Returns description of the framework this process is running on. + Value is based on RuntimeInformation.FrameworkDescription. + + + + + Returns version of the common language runtime this process is running on. + Value is based on Environment.Version. + + + + + Returns the TFM of the Grpc.Core assembly. + + + + + grpcsharp_request_call_context + + + + + Safe handle to wrap native objects. + + + + + Handler used for unimplemented method. + + + + + grpc_server_credentials from grpc/grpc_security.h + + + + + Writes responses asynchronously to an underlying AsyncCallServer object. + + + + + Details of a newly received RPC. + + + + + grpc_server from grpc/grpc.h + + + + + Maps methods from ServerServiceDefinition to server call handlers. + + + + + Helper for converting ServerServiceDefinition to server call handlers. + + + + + Slice of native memory. + Rough equivalent of grpc_slice (but doesn't support inlined slices, just a pointer to data and length) + + + + + Returns a that represents the current . + + + + + Represents grpc_slice_buffer with some extra utility functions to allow + writing data to it using the IBufferWriter interface. + + + + + gpr_timespec from grpc/support/time.h + + + + + Indicates whether this instance and a specified object are equal. + + + + + Returns the hash code for this instance. + + + + + Returns the full type name of this instance. + + + + + Indicates whether this instance and a specified object are equal. + + + + + Timespec a long time in the future. + + + + + Timespec a long time in the past. + + + + + Return Timespec representing the current time. + + + + + Seconds since unix epoch. + + + + + The nanoseconds part of timeval. + + + + + Converts the timespec to desired clock type. + + + + + Converts Timespec to DateTime. + Timespec needs to be of type GPRClockType.Realtime and needs to represent a legal value. + DateTime has lower resolution (100ns), so rounding can occurs. + Value are always rounded up to the nearest DateTime value in the future. + + For Timespec.InfFuture or if timespec is after the largest representable DateTime, DateTime.MaxValue is returned. + For Timespec.InfPast or if timespec is before the lowest representable DateTime, DateTime.MinValue is returned. + + Unless DateTime.MaxValue or DateTime.MinValue is returned, the resulting DateTime is always in UTC + (DateTimeKind.Utc) + + + + + Creates DateTime to Timespec. + DateTime has to be in UTC (DateTimeKind.Utc) unless it's DateTime.MaxValue or DateTime.MinValue. + For DateTime.MaxValue of date time after the largest representable Timespec, Timespec.InfFuture is returned. + For DateTime.MinValue of date time before the lowest representable Timespec, Timespec.InfPast is returned. + + The date time. + Date time. + + + + Gets current timestamp using GPRClockType.Precise. + Only available internally because core needs to be compiled with + GRPC_TIMERS_RDTSC support for this to use RDTSC. + + + + + Call invoker that throws NotImplementedException for all requests. + + + + + Represents a dynamically loaded unmanaged library in a (partially) platform independent manner. + First, the native library is loaded using dlopen (on Unix systems) or using LoadLibrary (on Windows). + dlsym or GetProcAddress are then used to obtain symbol addresses. Marshal.GetDelegateForFunctionPointer + transforms the addresses into delegates to native methods. + See http://stackoverflow.com/questions/13461989/p-invoke-to-dynamically-loaded-library-on-mono. + + + + + Loads symbol in a platform specific way. + + + + + + + Loads library in a platform specific way. + + + + + On Linux systems, using dlopen and dlsym results in + DllNotFoundException("libdl.so not found") if libc6-dev + is not installed. As a workaround, we load symbols for + dlopen and dlsym from the current process as on Linux + Mono sure is linked against these symbols. + + + + + Similarly as for Mono on Linux, we load symbols for + dlopen and dlsym from the "libcoreclr.so", + to avoid the dependency on libc-dev Linux. + + + + + Helps constructing the grpc-csharp component of the user agent string. + + + + + Utility type for identifying "well-known" strings (i.e. headers/keys etc that + we expect to see frequently, and don't want to allocate lots of copies of) + + + + + Test whether the provided byte sequence is recognized as a well-known string; if + so, return a shared instance of that string; otherwise, return null + + + + + Test whether the provided byte sequence is recognized as a well-known string; if + so, return a shared instance of that string; otherwise, return null + + + + + Default implementation of ServerCallContext. + + + + + Creates a new instance of ServerCallContext. + To allow reuse of ServerCallContext API by different gRPC implementations, the implementation of some members is provided externally. + To provide state, this ServerCallContext instance and extraData will be passed to the member implementations. + + + + Logger that logs to System.Console. + + + Creates a console logger not associated to any specific type. + + + Creates a console logger that logs messsage specific for given type. + + + + Returns a logger associated with the specified type. + + + + For logging messages. + + + Returns a logger associated with the specified type. + + + Logs a message with severity Debug. + + + Logs a formatted message with severity Debug. + + + Logs a message with severity Info. + + + Logs a formatted message with severity Info. + + + Logs a message with severity Warning. + + + Logs a formatted message with severity Warning. + + + Logs a message and an associated exception with severity Warning. + + + Logs a message with severity Error. + + + Logs a formatted message with severity Error. + + + Logs a message and an associated exception with severity Error. + + + Standard logging levels. + + + + Debug severity. + + + + + Info severity. + + + + + Warning severity. + + + + + Error severity. + + + + + Logging is off. + + + + Logger that filters out messages below certain log level. + + + + Creates and instance of LogLevelFilter. + + + + + Creates and instance of LogLevelFilter. + The fromEnvironmentVariable parameter allows looking up "GRPC_VERBOSITY" setting provided by C-core + and uses the same log level for C# logs. Using this setting is recommended as it can prevent unintentionally hiding + C core logs requested by "GRPC_VERBOSITY" environment variable (which could happen if C# logger's log level was set to a more restrictive value). + + the logger to forward filtered logs to. + the default log level, unless overriden by env variable. + if true, override log level with setting from environment variable. + + + + Returns a logger associated with the specified type. + + + + Logs a message with severity Debug. + + + Logs a formatted message with severity Debug. + + + Logs a message with severity Info. + + + Logs a formatted message with severity Info. + + + Logs a message with severity Warning. + + + Logs a formatted message with severity Warning. + + + Logs a message and an associated exception with severity Warning. + + + Logs a message with severity Error. + + + Logs a formatted message with severity Error. + + + Logs a message and an associated exception with severity Error. + + + Get log level based on a default and lookup of GRPC_VERBOSITY environment variable. + + + + Logger which doesn't log any information anywhere. + + + + + As with all logging calls on this logger, this method is a no-op. + + + + + As with all logging calls on this logger, this method is a no-op. + + + + + As with all logging calls on this logger, this method is a no-op. + + + + + As with all logging calls on this logger, this method is a no-op. + + + + + As with all logging calls on this logger, this method is a no-op. + + + + + Returns a reference to the instance on which the method is called, as + instances aren't associated with specific types. + + + + + As with all logging calls on this logger, this method is a no-op. + + + + + As with all logging calls on this logger, this method is a no-op. + + + + + As with all logging calls on this logger, this method is a no-op. + + + + + As with all logging calls on this logger, this method is a no-op. + + + + + As with all logging calls on this logger, this method is a no-op. + + + + Logger that logs to an arbitrary System.IO.TextWriter. + + + + Creates a console logger not associated to any specific type and writes to given System.IO.TextWriter. + User is responsible for providing an instance of TextWriter that is thread-safe. + + + + + Creates a console logger not associated to any specific type and writes to a System.IO.TextWriter obtained from given provider. + User is responsible for providing an instance of TextWriter that is thread-safe. + + + + Creates a console logger that logs messsage specific for given type. + + + + Returns a logger associated with the specified type. + + + + Logs a message with severity Debug. + + + Logs a formatted message with severity Debug. + + + Logs a message with severity Info. + + + Logs a formatted message with severity Info. + + + Logs a message with severity Warning. + + + Logs a formatted message with severity Warning. + + + Logs a message and an associated exception with severity Warning. + + + Logs a message with severity Error. + + + Logs a formatted message with severity Error. + + + Logs a message and an associated exception with severity Error. + + + Gets the type associated with this logger. + + + + gRPC server. A single server can serve an arbitrary number of services and can listen on more than one port. + + + + + Creates a new server. + + + + + Creates a new server. + + Channel options. + + + + Services that will be exported by the server once started. Register a service with this + server by adding its definition to this collection. + + + + + Ports on which the server will listen once started. Register a port with this + server by adding its definition to this collection. + + + + + To allow awaiting termination of the server. + + + + + Experimental API. Might anytime change without prior notice. + Number or calls requested via grpc_server_request_call at any given time for each completion queue. + + + + + Starts the server. + Throws IOException if not all ports have been bound successfully (see Ports.Add method). + Even if some of that ports haven't been bound, the server will still serve normally on all ports that have been + bound successfully (and the user is expected to shutdown the server by invoking ShutdownAsync or KillAsync). + + + + + Requests server shutdown and when there are no more calls being serviced, + cleans up used resources. The returned task finishes when shutdown procedure + is complete. + + + It is strongly recommended to shutdown all previously created servers before exiting from the process. + + + + + Requests server shutdown while cancelling all the in-progress calls. + The returned task finishes when shutdown procedure is complete. + + + It is strongly recommended to shutdown all previously created servers before exiting from the process. + + + + + Shuts down the server. + + + + + In case the environment's threadpool becomes dead, the shutdown completion will + never be delivered, but we need to release the environment's handle anyway. + + + + + Adds a service definition. + + + + + Adds a listening port. + + + + + Allows one new RPC call to be received by server. + + + + + Checks that all ports have been bound successfully. + + + + + Selects corresponding handler for given call and handles the call. + + + + + Handles the native callback. + + + + + Handles native callback. + + + + + Collection of service definitions. + + + + + Adds a service definition to the server. This is how you register + handlers for a service with the server. Only call this before Start(). + + + + + Gets enumerator for this collection. + + + + + Collection of server ports. + + + + + Adds a new port on which server should listen. + Only call this before Start(). + The port on which server will be listening. Return value of zero means that binding the port has failed. + + + + + Adds a new port on which server should listen. + The port on which server will be listening. Return value of zero means that binding the port has failed. + + the host + the port. If zero, an unused port is chosen automatically. + credentials to use to secure this port. + + + + Gets enumerator for this collection. + + + + + Server side credentials. + + + + + Returns instance of credential that provides no security and + will result in creating an unsecure server port with no encryption whatsoever. + + + + + Creates native object for the credentials. + + The native credentials. + + + + Modes of requesting client's SSL certificate by the server. + Corresponds to grpc_ssl_client_certificate_request_type. + + + + + Server does not request client certificate. + The certificate presented by the client is not checked by the server at + all. (A client may present a self signed or signed certificate or not + present a certificate at all and any of those option would be accepted) + + + + + Server requests client certificate but does not enforce that the client + presents a certificate. + If the client presents a certificate, the client authentication is left to + the application (the necessary metadata will be available to the + application via authentication context properties, see grpc_auth_context). + The client's key certificate pair must be valid for the SSL connection to + be established. + + + + + Server requests client certificate but does not enforce that the client + presents a certificate. + If the client presents a certificate, the client authentication is done by + the gRPC framework. (For a successful connection the client needs to either + present a certificate that can be verified against the root certificate + configured by the server or not present a certificate at all) + The client's key certificate pair must be valid for the SSL connection to + be established. + + + + + Server requests client certificate and enforces that the client presents a + certificate. + If the client presents a certificate, the client authentication is left to + the application (the necessary metadata will be available to the + application via authentication context properties, see grpc_auth_context). + The client's key certificate pair must be valid for the SSL connection to + be established. + + + + + Server requests client certificate and enforces that the client presents a + certificate. + The certificate presented by the client is verified by the gRPC framework. + (For a successful connection the client needs to present a certificate that + can be verified against the root certificate configured by the server) + The client's key certificate pair must be valid for the SSL connection to + be established. + + + + + Server-side SSL credentials. + + + + + Creates server-side SSL credentials. + + Key-certificates to use. + PEM encoded client root certificates used to authenticate client. + Deprecated, use clientCertificateRequest overload instead. + + + + Creates server-side SSL credentials. + + Key-certificates to use. + PEM encoded client root certificates used to authenticate client. + Options for requesting and verifying client certificate. + + + + Creates server-side SSL credentials. + This constructor should be used if you do not wish to authenticate the client. + (client certificate won't be requested and checked by the server at all). + + Key-certificates to use. + + + + Key-certificate pairs. + + + + + PEM encoded client root certificates. + + + + + Deprecated. If true, the authenticity of client check will be enforced. + + + + + Mode of requesting certificate from client by the server. + + + + + A port exposed by a server. + + + + + Pass this value as port to have the server choose an unused listening port for you. + Ports added to a server will contain the bound port in their property. + + + + + Creates a new port on which server should listen. + + The port on which server will be listening. + the host + the port. If zero, an unused port is chosen automatically. + credentials to use to secure this port. + + + + Creates a port from an existing ServerPort instance and boundPort value. + + + + The host. + + + The port. + + + The server credentials. + + + + The port actually bound by the server. This is useful if you let server + pick port automatically. + + + + + Extension methods that simplify work with gRPC streaming calls. + + + + + Reads the entire stream and executes an async action for each element. + + + + + Reads the entire stream and creates a list containing all the elements read. + + + + + Writes all elements from given enumerable to the stream. + Completes the stream afterwards unless close = false. + + + + + Writes all elements from given enumerable to the stream. + + + + + Utility methods to run microbenchmarks. + + + + + Runs a simple benchmark preceded by warmup phase. + + + + + Utility methods for task parallel library. + + + + + Framework independent equivalent of Task.CompletedTask. + + + + diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45/Grpc.Core.xml.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45/Grpc.Core.xml.meta new file mode 100644 index 00000000..2c1a5329 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/lib/net45/Grpc.Core.xml.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: ec9cf7702008ac648af0687c05064f78 +timeCreated: 1531219386 +licenseType: Free +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes.meta new file mode 100644 index 00000000..921669fd --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 643bdb9ca01174f4eb77e3e15f8324b3 +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/grpc_csharp_ext_dummy_stubs.c b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/grpc_csharp_ext_dummy_stubs.c new file mode 100644 index 00000000..11097e61 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/grpc_csharp_ext_dummy_stubs.c @@ -0,0 +1,440 @@ + +// Copyright 2019 The gRPC Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// When building for Unity Android with il2cpp backend, Unity tries to link +// the __Internal PInvoke definitions (which are required by iOS) even though +// the .so/.dll will be actually used. This file provides dummy stubs to +// make il2cpp happy. +// See https://github.com/grpc/grpc/issues/16012 + +#include +#include + +void grpcsharp_init() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_shutdown() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_version_string() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_batch_context_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_batch_context_recv_initial_metadata() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_batch_context_recv_message_length() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_batch_context_recv_message_next_slice_peek() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_batch_context_recv_status_on_client_status() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_batch_context_recv_status_on_client_details() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_batch_context_recv_status_on_client_error_string() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_batch_context_recv_status_on_client_trailing_metadata() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_batch_context_recv_close_on_server_cancelled() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_batch_context_reset() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_batch_context_destroy() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_request_call_context_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_request_call_context_call() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_request_call_context_method() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_request_call_context_host() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_request_call_context_deadline() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_request_call_context_request_metadata() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_request_call_context_reset() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_request_call_context_destroy() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_composite_call_credentials_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_credentials_release() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_cancel() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_cancel_with_status() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_start_unary() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_start_client_streaming() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_start_server_streaming() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_start_duplex_streaming() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_send_message() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_send_close_from_client() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_send_status_from_server() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_recv_message() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_recv_initial_metadata() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_start_serverside() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_send_initial_metadata() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_set_credentials() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_get_peer() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_destroy() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_channel_args_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_channel_args_set_string() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_channel_args_set_integer() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_channel_args_destroy() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_override_default_ssl_roots() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_ssl_credentials_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_composite_channel_credentials_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_channel_credentials_release() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_insecure_channel_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_secure_channel_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_channel_create_call() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_channel_check_connectivity_state() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_channel_watch_connectivity_state() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_channel_get_target() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_channel_destroy() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_sizeof_grpc_event() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_completion_queue_create_async() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_completion_queue_create_sync() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_completion_queue_shutdown() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_completion_queue_next() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_completion_queue_pluck() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_completion_queue_destroy() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void gprsharp_free() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_metadata_array_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_metadata_array_add() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_metadata_array_count() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_metadata_array_get_key() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_metadata_array_get_value() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_metadata_array_destroy_full() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_redirect_log() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_native_callback_dispatcher_init() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_metadata_credentials_create_from_plugin() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_metadata_credentials_notify_from_plugin() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_ssl_server_credentials_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_server_credentials_release() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_server_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_server_register_completion_queue() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_server_add_insecure_http2_port() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_server_add_secure_http2_port() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_server_start() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_server_request_call() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_server_cancel_all_calls() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_server_shutdown_and_notify_callback() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_server_destroy() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_call_auth_context() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_auth_context_peer_identity_property_name() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_auth_context_property_iterator() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_auth_property_iterator_next() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_auth_context_release() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_slice_buffer_create() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_slice_buffer_adjust_tail_space() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_slice_buffer_slice_count() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_slice_buffer_slice_peek() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_slice_buffer_reset_and_unref() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_slice_buffer_destroy() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void gprsharp_now() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void gprsharp_inf_future() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void gprsharp_inf_past() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void gprsharp_convert_clock_type() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void gprsharp_sizeof_timespec() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_test_callback() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_test_nop() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_test_override_method() { + fprintf(stderr, "Should never reach here"); + abort(); +} +void grpcsharp_test_call_start_unary_echo() { + fprintf(stderr, "Should never reach here"); + abort(); +} diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/grpc_csharp_ext_dummy_stubs.c.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/grpc_csharp_ext_dummy_stubs.c.meta new file mode 100644 index 00000000..d93af38e --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/grpc_csharp_ext_dummy_stubs.c.meta @@ -0,0 +1,93 @@ +fileFormatVersion: 2 +guid: 576b78662f1f8af4fa751f709b620f52 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 0 + Exclude Editor: 1 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXUniversal: 1 + Exclude Win: 0 + Exclude Win64: 0 + - first: + Android: Android + second: + enabled: 1 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + CPU: AnyCPU + DefaultValueInitialized: true + OS: AnyOS + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: LinuxUniversal + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/linux.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/linux.meta new file mode 100644 index 00000000..9fc0e647 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/linux.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 1ff40de7dc502c14e8893c7679e9f44a +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/linux/x64.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/linux/x64.meta new file mode 100644 index 00000000..28d3c0fd --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/linux/x64.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 08ccfdbfbd8d2d6458eb44d41a7b0b0a +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/linux/x64/libgrpc_csharp_ext.so.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/linux/x64/libgrpc_csharp_ext.so.meta new file mode 100644 index 00000000..0d639762 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/linux/x64/libgrpc_csharp_ext.so.meta @@ -0,0 +1,117 @@ +fileFormatVersion: 2 +guid: c176dc12f2803e14bb37bcd0ba4a0718 +timeCreated: 1531219386 +licenseType: Free +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux: 1 + Exclude Linux64: 0 + Exclude LinuxUniversal: 0 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 0 + Exclude Win64: 0 + Exclude iOS: 1 + - first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: Linux + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Standalone: LinuxUniversal + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: OSXIntel64 + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + iPhone: iOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx.meta new file mode 100644 index 00000000..cc9c9b60 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7b1ebe888da0a174c95a712766d2558c +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx/x64.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx/x64.meta new file mode 100644 index 00000000..d01c158c --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx/x64.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ccea531b15a71974a91329186dd65075 +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx/x64/grpc_csharp_ext.bundle b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx/x64/grpc_csharp_ext.bundle new file mode 100644 index 00000000..9745184f Binary files /dev/null and b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx/x64/grpc_csharp_ext.bundle differ diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx/x64/grpc_csharp_ext.bundle.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx/x64/grpc_csharp_ext.bundle.meta new file mode 100644 index 00000000..9d192f59 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/osx/x64/grpc_csharp_ext.bundle.meta @@ -0,0 +1,117 @@ +fileFormatVersion: 2 +guid: da53c729add26524fbecb84a7b599289 +timeCreated: 1531219386 +licenseType: Free +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux: 1 + Exclude Linux64: 1 + Exclude LinuxUniversal: 1 + Exclude OSXIntel: 1 + Exclude OSXIntel64: 0 + Exclude OSXUniversal: 0 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 1 + - first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: OSX + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Linux + second: + enabled: 0 + settings: + CPU: x86 + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: x86_64 + - first: + Standalone: LinuxUniversal + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: OSXIntel + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: OSXIntel64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + iPhone: iOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win.meta new file mode 100644 index 00000000..1491ee6f --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 928a9392668000344b70b6fd126e522c +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x64.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x64.meta new file mode 100644 index 00000000..ac2a063f --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x64.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 34969b8c99d7a934eaa5e84da9fcf326 +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x64/grpc_csharp_ext.dll.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x64/grpc_csharp_ext.dll.meta new file mode 100644 index 00000000..a42f84fc --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x64/grpc_csharp_ext.dll.meta @@ -0,0 +1,117 @@ +fileFormatVersion: 2 +guid: cb634ddbaed75c344a6b79bc91ca996e +timeCreated: 1531219386 +licenseType: Free +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux: 0 + Exclude Linux64: 0 + Exclude LinuxUniversal: 0 + Exclude OSXIntel: 0 + Exclude OSXIntel64: 0 + Exclude OSXUniversal: 0 + Exclude Win: 1 + Exclude Win64: 0 + Exclude iOS: 1 + - first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: Windows + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: None + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Standalone: Linux + second: + enabled: 1 + settings: + CPU: x86 + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Standalone: LinuxUniversal + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: OSXIntel + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: OSXIntel64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + iPhone: iOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x86.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x86.meta new file mode 100644 index 00000000..f3eb146c --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x86.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: ed5c6044f868f9a4f955b7db2d2df619 +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x86/grpc_csharp_ext.dll.meta b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x86/grpc_csharp_ext.dll.meta new file mode 100644 index 00000000..bd6291ea --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/Grpc.Core/runtimes/win/x86/grpc_csharp_ext.dll.meta @@ -0,0 +1,117 @@ +fileFormatVersion: 2 +guid: fe9aa1338bfc3864eb50df0f9d648316 +timeCreated: 1531219386 +licenseType: Free +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + '': Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux: 0 + Exclude Linux64: 0 + Exclude LinuxUniversal: 0 + Exclude OSXIntel: 0 + Exclude OSXIntel64: 0 + Exclude OSXUniversal: 0 + Exclude Win: 0 + Exclude Win64: 1 + Exclude iOS: 1 + - first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86 + DefaultValueInitialized: true + OS: Windows + - first: + Facebook: Win + second: + enabled: 0 + settings: + CPU: AnyCPU + - first: + Facebook: Win64 + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Linux + second: + enabled: 1 + settings: + CPU: x86 + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Standalone: LinuxUniversal + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: OSXIntel + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: OSXIntel64 + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: OSXUniversal + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: Win + second: + enabled: 1 + settings: + CPU: AnyCPU + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: None + - first: + iPhone: iOS + second: + enabled: 0 + settings: + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers.meta new file mode 100644 index 00000000..cff9ce28 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4fc40716435458b42bf1496a65d95d83 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers/lib.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers/lib.meta new file mode 100644 index 00000000..754fcaee --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers/lib.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 0cb4be3dca2a49e6a920da037ea13d80 +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers/lib/net45.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers/lib/net45.meta new file mode 100644 index 00000000..00368db2 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers/lib/net45.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 53b3f7a608814da5a3e3207d10c85b4e +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers/lib/net45/System.Buffers.dll.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers/lib/net45/System.Buffers.dll.meta new file mode 100644 index 00000000..6a9eae1c --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Buffers/lib/net45/System.Buffers.dll.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: bb037a236f584460af82c59c5d5ad972 +timeCreated: 1531219386 +licenseType: Free +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory.meta new file mode 100644 index 00000000..ed80273f --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5f396723917087e429b7eb79f1773a4c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory/lib.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory/lib.meta new file mode 100644 index 00000000..eab98519 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory/lib.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 3d6c20bf92b74c03b1ba691cbce610e4 +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory/lib/net45.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory/lib/net45.meta new file mode 100644 index 00000000..2d33fd95 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory/lib/net45.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 7164a0a387b24d1a9d76f6d558fc44d2 +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory/lib/net45/System.Memory.dll.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory/lib/net45/System.Memory.dll.meta new file mode 100644 index 00000000..11af5eae --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Memory/lib/net45/System.Memory.dll.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: e774d51b8ba64a988dd37135e487105c +timeCreated: 1531219386 +licenseType: Free +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe.meta new file mode 100644 index 00000000..804cb02e --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a2e5c05e5efd94e47a925b0cace0dadf +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe/lib.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe/lib.meta new file mode 100644 index 00000000..b3a382ae --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe/lib.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: f51cc0f065424fb2928eee7c2804bfd8 +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe/lib/net45.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe/lib/net45.meta new file mode 100644 index 00000000..41542419 --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe/lib/net45.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: aad21c5c1f2f4c1391b1e4a475f163bb +folderAsset: yes +timeCreated: 1531219385 +licenseType: Free +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe/lib/net45/System.Runtime.CompilerServices.Unsafe.dll.meta b/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe/lib/net45/System.Runtime.CompilerServices.Unsafe.dll.meta new file mode 100644 index 00000000..c3988cad --- /dev/null +++ b/csharp/examples/unity/Assets/Plugins/Grpc/System.Runtime.CompilerServices.Unsafe/lib/net45/System.Runtime.CompilerServices.Unsafe.dll.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: d378b9cd266a4a448f071c114e5f18cb +timeCreated: 1531219386 +licenseType: Free +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + isPreloaded: 0 + isOverridable: 0 + platformData: + - first: + Any: + second: + enabled: 1 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: + CPU: AnyCPU + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scenes.meta b/csharp/examples/unity/Assets/Scenes.meta new file mode 100644 index 00000000..b207b915 --- /dev/null +++ b/csharp/examples/unity/Assets/Scenes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3603634ca584ba9478b8010240496bc1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scenes/SampleScene.unity b/csharp/examples/unity/Assets/Scenes/SampleScene.unity new file mode 100644 index 00000000..923744b9 --- /dev/null +++ b/csharp/examples/unity/Assets/Scenes/SampleScene.unity @@ -0,0 +1,781 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 3 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_IndirectSpecularColor: {r: 0, g: 0, b: 0, a: 1} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_GIWorkflowMode: 1 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 0 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 12 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_FinalGather: 0 + m_FinalGatherFiltering: 1 + m_FinalGatherRayCount: 256 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 0 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 500 + m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 500 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 2 + m_PVRDenoiserTypeDirect: 0 + m_PVRDenoiserTypeIndirect: 0 + m_PVRDenoiserTypeAO: 0 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVREnvironmentMIS: 0 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 5 + m_PVRFilteringGaussRadiusAO: 2 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_LightProbeSampleCountMultiplier: 4 + m_LightingDataAsset: {fileID: 0} + m_UseShadowmask: 1 +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &50986617 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 50986618} + - component: {fileID: 50986620} + - component: {fileID: 50986619} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &50986618 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 50986617} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 1300105461} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &50986619 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 50986617} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_RaycastTarget: 1 + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 14 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 10 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Terminate Pitaya +--- !u!222 &50986620 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 50986617} + m_CullTransparentMesh: 0 +--- !u!1 &323648781 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 323648782} + - component: {fileID: 323648785} + - component: {fileID: 323648784} + - component: {fileID: 323648783} + m_Layer: 5 + m_Name: startBtn + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &323648782 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 323648781} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 1679775895} + m_Father: {fileID: 1890302868} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0.5, y: 0.5} + m_AnchorMax: {x: 0.5, y: 0.5} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 160, y: 30} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &323648783 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 323648781} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 1, g: 1, b: 1, a: 1} + m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_SelectedTrigger: Selected + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 323648784} + m_OnClick: + m_PersistentCalls: + m_Calls: [] +--- !u!114 &323648784 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 323648781} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 +--- !u!222 &323648785 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 323648781} + m_CullTransparentMesh: 0 +--- !u!1 &519420028 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 519420032} + - component: {fileID: 519420031} + - component: {fileID: 519420029} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!81 &519420029 +AudioListener: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 519420028} + m_Enabled: 1 +--- !u!20 &519420031 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 519420028} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 2 + m_BackGroundColor: {r: 0.19215687, g: 0.3019608, b: 0.4745098, a: 0} + m_projectionMatrixMode: 1 + m_GateFitMode: 2 + m_FOVAxisMode: 0 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_FocalLength: 50 + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 1 + orthographic size: 5 + m_Depth: -1 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 0 + m_HDR: 1 + m_AllowMSAA: 0 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 0 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &519420032 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 519420028} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: -10} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1300105460 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1300105461} + - component: {fileID: 1300105464} + - component: {fileID: 1300105463} + - component: {fileID: 1300105462} + m_Layer: 5 + m_Name: stopBtn + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1300105461 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1300105460} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: + - {fileID: 50986618} + m_Father: {fileID: 1890302868} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0.5, y: 0.5} + m_AnchorMax: {x: 0.5, y: 0.5} + m_AnchoredPosition: {x: 0, y: -38.2} + m_SizeDelta: {x: 160, y: 30} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1300105462 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1300105460} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 4e29b1a8efbd4b44bb3f3716e73f07ff, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Navigation: + m_Mode: 3 + m_SelectOnUp: {fileID: 0} + m_SelectOnDown: {fileID: 0} + m_SelectOnLeft: {fileID: 0} + m_SelectOnRight: {fileID: 0} + m_Transition: 1 + m_Colors: + m_NormalColor: {r: 1, g: 1, b: 1, a: 1} + m_HighlightedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_PressedColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 1} + m_SelectedColor: {r: 0.9607843, g: 0.9607843, b: 0.9607843, a: 1} + m_DisabledColor: {r: 0.78431374, g: 0.78431374, b: 0.78431374, a: 0.5019608} + m_ColorMultiplier: 1 + m_FadeDuration: 0.1 + m_SpriteState: + m_HighlightedSprite: {fileID: 0} + m_PressedSprite: {fileID: 0} + m_SelectedSprite: {fileID: 0} + m_DisabledSprite: {fileID: 0} + m_AnimationTriggers: + m_NormalTrigger: Normal + m_HighlightedTrigger: Highlighted + m_PressedTrigger: Pressed + m_SelectedTrigger: Selected + m_DisabledTrigger: Disabled + m_Interactable: 1 + m_TargetGraphic: {fileID: 1300105463} + m_OnClick: + m_PersistentCalls: + m_Calls: [] +--- !u!114 &1300105463 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1300105460} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: fe87c0e1cc204ed48ad3b37840f39efc, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 1, g: 1, b: 1, a: 1} + m_RaycastTarget: 1 + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_Sprite: {fileID: 10905, guid: 0000000000000000f000000000000000, type: 0} + m_Type: 1 + m_PreserveAspect: 0 + m_FillCenter: 1 + m_FillMethod: 4 + m_FillAmount: 1 + m_FillClockwise: 1 + m_FillOrigin: 0 + m_UseSpriteMesh: 0 + m_PixelsPerUnitMultiplier: 1 +--- !u!222 &1300105464 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1300105460} + m_CullTransparentMesh: 0 +--- !u!1 &1624148669 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1624148672} + - component: {fileID: 1624148671} + - component: {fileID: 1624148670} + m_Layer: 0 + m_Name: EventSystem + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1624148670 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1624148669} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 4f231c4fb786f3946a6b90b886c48677, type: 3} + m_Name: + m_EditorClassIdentifier: + m_HorizontalAxis: Horizontal + m_VerticalAxis: Vertical + m_SubmitButton: Submit + m_CancelButton: Cancel + m_InputActionsPerSecond: 10 + m_RepeatDelay: 0.5 + m_ForceModuleActive: 0 +--- !u!114 &1624148671 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1624148669} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 76c392e42b5098c458856cdf6ecaaaa1, type: 3} + m_Name: + m_EditorClassIdentifier: + m_FirstSelected: {fileID: 0} + m_sendNavigationEvents: 1 + m_DragThreshold: 10 +--- !u!4 &1624148672 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1624148669} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 0} + m_RootOrder: 2 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1679775894 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1679775895} + - component: {fileID: 1679775897} + - component: {fileID: 1679775896} + m_Layer: 5 + m_Name: Text + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!224 &1679775895 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1679775894} + m_LocalRotation: {x: -0, y: -0, z: -0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_Children: [] + m_Father: {fileID: 323648782} + m_RootOrder: 0 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 1, y: 1} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0.5, y: 0.5} +--- !u!114 &1679775896 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1679775894} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 5f7201a12d95ffc409449d95f23cf332, type: 3} + m_Name: + m_EditorClassIdentifier: + m_Material: {fileID: 0} + m_Color: {r: 0.19607843, g: 0.19607843, b: 0.19607843, a: 1} + m_RaycastTarget: 1 + m_Maskable: 1 + m_OnCullStateChanged: + m_PersistentCalls: + m_Calls: [] + m_FontData: + m_Font: {fileID: 10102, guid: 0000000000000000e000000000000000, type: 0} + m_FontSize: 14 + m_FontStyle: 0 + m_BestFit: 0 + m_MinSize: 10 + m_MaxSize: 40 + m_Alignment: 4 + m_AlignByGeometry: 0 + m_RichText: 1 + m_HorizontalOverflow: 0 + m_VerticalOverflow: 0 + m_LineSpacing: 1 + m_Text: Initialize Pitaya +--- !u!222 &1679775897 +CanvasRenderer: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1679775894} + m_CullTransparentMesh: 0 +--- !u!1 &1890302864 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1890302868} + - component: {fileID: 1890302867} + - component: {fileID: 1890302866} + - component: {fileID: 1890302865} + - component: {fileID: 1890302869} + m_Layer: 5 + m_Name: Canvas + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &1890302865 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1890302864} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: dc42784cf147c0c48a680349fa168899, type: 3} + m_Name: + m_EditorClassIdentifier: + m_IgnoreReversedGraphics: 1 + m_BlockingObjects: 0 + m_BlockingMask: + serializedVersion: 2 + m_Bits: 4294967295 +--- !u!114 &1890302866 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1890302864} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 0cd44c1031e13a943bb63640046fad76, type: 3} + m_Name: + m_EditorClassIdentifier: + m_UiScaleMode: 0 + m_ReferencePixelsPerUnit: 100 + m_ScaleFactor: 1 + m_ReferenceResolution: {x: 800, y: 600} + m_ScreenMatchMode: 0 + m_MatchWidthOrHeight: 0 + m_PhysicalUnit: 3 + m_FallbackScreenDPI: 96 + m_DefaultSpriteDPI: 96 + m_DynamicPixelsPerUnit: 1 +--- !u!223 &1890302867 +Canvas: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1890302864} + m_Enabled: 1 + serializedVersion: 3 + m_RenderMode: 0 + m_Camera: {fileID: 0} + m_PlaneDistance: 100 + m_PixelPerfect: 0 + m_ReceivesEvents: 1 + m_OverrideSorting: 0 + m_OverridePixelPerfect: 0 + m_SortingBucketNormalizedSize: 0 + m_AdditionalShaderChannelsFlag: 0 + m_SortingLayerID: 0 + m_SortingOrder: 0 + m_TargetDisplay: 0 +--- !u!224 &1890302868 +RectTransform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1890302864} + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 0, y: 0, z: 0} + m_Children: + - {fileID: 323648782} + - {fileID: 1300105461} + m_Father: {fileID: 0} + m_RootOrder: 1 + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} + m_AnchorMin: {x: 0, y: 0} + m_AnchorMax: {x: 0, y: 0} + m_AnchoredPosition: {x: 0, y: 0} + m_SizeDelta: {x: 0, y: 0} + m_Pivot: {x: 0, y: 0} +--- !u!114 &1890302869 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1890302864} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 97dfcc7c063aea94c9e6cb41b2fcd3f5, type: 3} + m_Name: + m_EditorClassIdentifier: + startBtn: {fileID: 323648783} + terminateBtn: {fileID: 1300105462} diff --git a/csharp/examples/unity/Assets/Scenes/SampleScene.unity.meta b/csharp/examples/unity/Assets/Scenes/SampleScene.unity.meta new file mode 100644 index 00000000..c1e3c88e --- /dev/null +++ b/csharp/examples/unity/Assets/Scenes/SampleScene.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 2cda990e2423bbf4892e6590ba056729 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts.meta b/csharp/examples/unity/Assets/Scripts.meta new file mode 100644 index 00000000..c8d96142 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 20e09d70a79b7b749b72860c2382e5fd +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya.meta b/csharp/examples/unity/Assets/Scripts/NPitaya.meta new file mode 100644 index 00000000..068d2826 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 52b51d96534ec8045a0e83ee52cc37ab +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Constants.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Constants.meta new file mode 100644 index 00000000..83e45c49 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Constants.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1952c4ea6cabb6e44b0ca99fe347a944 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Constants/Routes.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Constants/Routes.cs new file mode 100644 index 00000000..4ce273c4 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Constants/Routes.cs @@ -0,0 +1,9 @@ +namespace NPitaya.Constants +{ + public class Routes + { + public static string SessionBindRoute = "sys.bindsession"; + public static string SessionPushRoute = "sys.pushsession"; + public static string SessionKickRoute = "sys.kick"; + } +} \ No newline at end of file diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Constants/Routes.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Constants/Routes.cs.meta new file mode 100644 index 00000000..c657cca0 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Constants/Routes.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3b2af9dee21837848b9ffa590510891b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics.meta new file mode 100644 index 00000000..87bbbfdf --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7f4245defb1d0b74bb4386ae139f7431 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/Constants.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/Constants.cs new file mode 100644 index 00000000..e14d0789 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/Constants.cs @@ -0,0 +1,43 @@ +using System; + +namespace NPitaya.Metrics +{ + public class Constants + { + internal static string PitayaKey = "pitaya"; + internal static string ResponseTimeMetricKey = "response_time_ns"; + internal static string ConnectedClientsMetricKey = "connected_clients"; + internal static string CountServersMetricKey = "count_servers"; + internal static string ChannelCapacityMetricKey = "channel_capacity"; + internal static string DroppedMessagesMetricKey = "dropped_messages"; + internal static string ProccessDelayMetricKey = "handler_delay_ns"; + internal static string GoroutinesMetricKey = "goroutines"; + internal static string HeapSizeMetricKey = "heapsize"; + internal static string HeapObjectsMetricKey = "heapobjects"; + internal static string WorkerJobsTotalMetricKey = "worker_jobs_total"; + internal static string WorkerJobsRetryMetricKey = "worker_jobs_retry_total"; + internal static string WorkerQueueSizeMetricKey = "worker_queue_size"; + internal static string ExceededRateLimitingMetricKey = "exceeded_rate_limiting"; + + public enum Status + { + fail, + success + } + + public class MetricNotFoundException : Exception + { + public MetricNotFoundException() + { + } + + public MetricNotFoundException(string message) : base(message) + { + } + + public MetricNotFoundException(string message, Exception inner) : base(message, inner) + { + } + } + } +} \ No newline at end of file diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/Constants.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/Constants.cs.meta new file mode 100644 index 00000000..4274c1c1 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/Constants.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 600c9b08645f9dc48adf2a54bf53ef9b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/IMetricsReporter.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/IMetricsReporter.cs new file mode 100644 index 00000000..a3ab76ee --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/IMetricsReporter.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; + +namespace NPitaya.Metrics +{ + public interface IMetricsReporter + { + void ReportCount(string metricKey, Dictionary labels, double value); + void ReportGauge(string metricKey, Dictionary labels, double value); + void ReportSummary(string metricKey, Dictionary labels, double value); + } +} \ No newline at end of file diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/IMetricsReporter.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/IMetricsReporter.cs.meta new file mode 100644 index 00000000..3f1ee40e --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/IMetricsReporter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9da5f578056a4e24bafaf73281ca12fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/MetricsReporters.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/MetricsReporters.cs new file mode 100644 index 00000000..65671df7 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/MetricsReporters.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +using System.Diagnostics; + +namespace NPitaya.Metrics +{ + public static class MetricsReporters + { + private static List _reporters = new List(); + + public static void AddMetricReporter(IMetricsReporter mr) + { + _reporters.Add(mr); + } + + public static void Terminate() + { + _reporters = new List(); + } + + public static void ReportMessageProccessDelay(string route, string type, Stopwatch sw) + { + var tags = new Dictionary { {"route", route}, {"type", type} }; + ReportSummary(Constants.ProccessDelayMetricKey, tags, sw.Elapsed.TotalMilliseconds * 1000000); + } + + public static void ReportTimer(string status, string route, string type, string code, Stopwatch sw) + { + var tags = new Dictionary { {"status", status}, {"route", route}, {"type", type}, {"code", code} }; + ReportSummary(Constants.ResponseTimeMetricKey, tags, sw.Elapsed.TotalMilliseconds * 1000000); + } + + public static void ReportNumberOfConnectedClients(double value) + { + ReportGauge(Constants.ConnectedClientsMetricKey, new Dictionary(), value); + } + + public static void ReportCount(string key, Dictionary tags, double value) + { + foreach (var reporter in _reporters) + { + reporter.ReportCount(key, tags, value); + } + } + public static void ReportGauge(string key, Dictionary tags, double value) + { + foreach (var reporter in _reporters) + { + reporter.ReportGauge(key, tags, value); + } + } + + public static void ReportSummary(string key, Dictionary tags, double value) + { + foreach (var reporter in _reporters) + { + reporter.ReportSummary(key, tags, value); + } + } + + } +} \ No newline at end of file diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/MetricsReporters.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/MetricsReporters.cs.meta new file mode 100644 index 00000000..1ce3e4bc --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/MetricsReporters.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c9a214f5e93c07f4aa8d6eac4d14fe17 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/PrometheusMetricsReporter.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/PrometheusMetricsReporter.cs new file mode 100644 index 00000000..b8a5470f --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/PrometheusMetricsReporter.cs @@ -0,0 +1,299 @@ +//using System.Collections.Generic; +//using System.Linq; +//using Prometheus; +// +//namespace NPitaya.Metrics +//{ +// public class CustomMetricsSpec +// { +// public List Summaries = new List(); +// public List Gauges = new List(); +// public List Counters = new List(); +// } +// +// public class CustomSummary +// { +// public string Subsystem; +// public string Name; +// public string Help; +// public Dictionary Objectives = new Dictionary(); +// public List Labels = new List(); +// } +// +// public class CustomGauge +// { +// public string Subsystem; +// public string Name; +// public string Help; +// public List Labels = new List(); +// } +// +// public class CustomCounter +// { +// public string Subsystem; +// public string Name; +// public string Help; +// public List Labels = new List(); +// } +// public class PrometheusMetricsReporter: IMetricsReporter +// { +// private Dictionary _additionalLabels; +// private Dictionary _constantLabels; +// private Dictionary _countReportersMap; +// private Dictionary _summaryReportersMap; +// private Dictionary _gaugeReportersMap; +// +// public PrometheusMetricsReporter(string serverType, string game, int port, Dictionary constantLabels = null, Dictionary additionalLabels = null, CustomMetricsSpec customMetricsSpec = null) +// { +// _constantLabels = constantLabels ?? new Dictionary(); +// _constantLabels["game"] = game; +// _constantLabels["serverType"] = serverType; +// _additionalLabels = additionalLabels ?? new Dictionary(); +// _countReportersMap = new Dictionary(); +// _summaryReportersMap = new Dictionary(); +// _gaugeReportersMap = new Dictionary(); +// +// if (customMetricsSpec != null) +// { +// _registerCustomMetrics(customMetricsSpec); +// } +// +// _registerMetrics(); +// +// var prometheusServer = new MetricServer(port: port); +// prometheusServer.Start(); +// } +// +// private void _registerCustomMetrics(CustomMetricsSpec customMetricsSpec) +// { +// foreach (var summary in customMetricsSpec.Summaries) +// { +// _addSummaryReporter( +// Constants.PitayaKey, +// summary.Subsystem, +// summary.Name, +// summary.Help, +// summary.Labels.ToArray(), +// summary.Objectives); +// } +// +// foreach (var gauge in customMetricsSpec.Gauges) +// { +// _addGaugeReporter( +// Constants.PitayaKey, +// gauge.Subsystem, +// gauge.Name, +// gauge.Help, +// gauge.Labels.ToArray()); +// } +// +// foreach (var counter in customMetricsSpec.Counters) +// { +// _addCounterReporter( +// Constants.PitayaKey, +// counter.Subsystem, +// counter.Name, +// counter.Help, +// counter.Labels.ToArray()); +// } +// } +// +// private void _registerMetrics() +// { +// _addSummaryReporter( +// Constants.PitayaKey, +// "handler", +// Constants.ResponseTimeMetricKey, +// "the time to process a msg in nanoseconds", +// new[]{"route", "status", "type", "code"}); +// +// _addSummaryReporter( +// Constants.PitayaKey, +// "handler", +// Constants.ProccessDelayMetricKey, +// "the delay to start processing a msg in nanoseconds", +// new[]{"route", "type"}); +// +// _addGaugeReporter( +// Constants.PitayaKey, +// "acceptor", +// Constants.ConnectedClientsMetricKey, +// "the number of clients connected right now", +// new string[]{}); +// +// _addGaugeReporter( +// Constants.PitayaKey, +// "service_discovery", +// Constants.CountServersMetricKey, +// "the number of discovered servers by service discovery", +// new[]{"type"}); +// +// _addGaugeReporter( +// Constants.PitayaKey, +// "channel", +// Constants.ChannelCapacityMetricKey, +// "the available capacity of the channel", +// new[]{"channel"}); +// +// _addGaugeReporter( +// Constants.PitayaKey, +// "rpc_server", +// Constants.DroppedMessagesMetricKey, +// "the number of rpc server dropped messages (messages that are not handled)", +// new string[]{}); +// +// _addGaugeReporter( +// Constants.PitayaKey, +// "sys", +// Constants.GoroutinesMetricKey, +// "the current number of goroutines", +// new string[]{}); +// +// _addGaugeReporter( +// Constants.PitayaKey, +// "sys", +// Constants.HeapSizeMetricKey, +// "the current heap size", +// new string[]{}); +// +// _addGaugeReporter( +// Constants.PitayaKey, +// "sys", +// Constants.HeapObjectsMetricKey, +// "the current number of allocated heap objects", +// new string[]{}); +// +// _addGaugeReporter( +// Constants.PitayaKey, +// "worker", +// Constants.WorkerJobsRetryMetricKey, +// "the current number of job retries", +// new string[]{}); +// +// _addGaugeReporter( +// Constants.PitayaKey, +// "worker", +// Constants.WorkerQueueSizeMetricKey, +// "the current queue size", +// new[]{"queue"}); +// +// _addGaugeReporter( +// Constants.PitayaKey, +// "worker", +// Constants.WorkerJobsTotalMetricKey, +// "the total executed jobs", +// new[]{"status"}); +// +// _addCounterReporter( +// Constants.PitayaKey, +// "acceptor", +// Constants.ExceededRateLimitingMetricKey, +// "the number of blocked requests by exceeded rate limiting", +// new string[]{}); +// } +// +// private void _addSummaryReporter(string metricNamespace, string metricSubsystem, string metricName, string metricHelp, string[] metricLabels, Dictionary objectives = null) +// { +// var allLabels = new List(); +// allLabels.AddRange(_constantLabels.Keys.ToArray()); +// allLabels.AddRange(_additionalLabels.Keys.ToArray()); +// allLabels.AddRange(metricLabels); +// var summaryObjectives = new List(); +// if (objectives != null) +// { +// foreach (var kv in objectives) +// { +// summaryObjectives.Add(new QuantileEpsilonPair(kv.Key, kv.Value)); +// } +// } +// else +// { +// summaryObjectives.Add(new QuantileEpsilonPair(0.7, 0.02)); +// summaryObjectives.Add(new QuantileEpsilonPair(0.95, 0.005)); +// summaryObjectives.Add(new QuantileEpsilonPair(0.99, 0.001)); +// } +// +// +// var summary = Prometheus.Metrics.CreateSummary(metricNamespace + "_" + metricSubsystem + "_" + metricName, metricHelp, new SummaryConfiguration +// { +// Objectives = summaryObjectives, +// LabelNames = allLabels.ToArray(), +// }); +// _summaryReportersMap[metricName] = summary; +// } +// +// private void _addCounterReporter(string metricNamespace, string metricSubsystem, string metricName, string metricHelp, string[] metricLabels) +// { +// var allLabels = new List(); +// allLabels.AddRange(_constantLabels.Keys.ToArray()); +// allLabels.AddRange(_additionalLabels.Keys.ToArray()); +// allLabels.AddRange(metricLabels); +// var counter = Prometheus.Metrics.CreateCounter(metricNamespace + "_" + metricSubsystem + "_" + metricName, metricHelp, new CounterConfiguration +// { +// LabelNames = allLabels.ToArray(), +// }); +// _countReportersMap[metricName] = counter; +// } +// +// private void _addGaugeReporter(string metricNamespace, string metricSubsystem, string metricName, string metricHelp, string[] metricLabels) +// { +// var allLabels = new List(); +// allLabels.AddRange(_constantLabels.Keys.ToArray()); +// allLabels.AddRange(_additionalLabels.Keys.ToArray()); +// allLabels.AddRange(metricLabels); +// var gauge = Prometheus.Metrics.CreateGauge(metricNamespace + "_" + metricSubsystem + "_" + metricName, metricHelp, new GaugeConfiguration +// { +// LabelNames = allLabels.ToArray(), +// }); +// _gaugeReportersMap[metricName] = gauge; +// } +// +// public void ReportCount(string metricKey, Dictionary tags, double value) +// { +// if (!_countReportersMap.TryGetValue(metricKey, out var counter)) return; +// var labelValues = _ensureLabels(tags, counter.LabelNames); +// counter.WithLabels(labelValues).Inc(value); +// } +// +// public void ReportGauge(string metricKey, Dictionary tags, double value) +// { +// if (!_gaugeReportersMap.TryGetValue(metricKey, out var gauge)) return; +// var labelValues = _ensureLabels(tags, gauge.LabelNames); +// gauge.WithLabels(labelValues).Set(value); +// } +// +// public void ReportSummary(string metricKey, Dictionary tags, double value) +// { +// if (!_summaryReportersMap.TryGetValue(metricKey, out var summary)) return; +// var labelValues = _ensureLabels(tags, summary.LabelNames); +// summary.WithLabels(labelValues).Observe(value); +// } +// +// private string[] _ensureLabels(Dictionary labels, string[] labelNames) +// { +// var labelValues = new List(); +// foreach (var lName in labelNames) +// { +// if (labels.TryGetValue(lName, out var lValue)) +// { +// labelValues.Add(lValue); +// continue; +// } +// if (_additionalLabels.TryGetValue(lName, out lValue)) +// { +// labelValues.Add(lValue); +// continue; +// } +// if (_constantLabels.TryGetValue(lName, out lValue)) +// { +// labelValues.Add(lValue); +// continue; +// } +// +// labelValues.Add(""); +// } +// +// return labelValues.ToArray(); +// } +// } +//} \ No newline at end of file diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/PrometheusMetricsReporter.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/PrometheusMetricsReporter.cs.meta new file mode 100644 index 00000000..e36b6d29 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/PrometheusMetricsReporter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c1383675b5f9ae4468f3644113f6b2a8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/StatsdMetricsReporter.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/StatsdMetricsReporter.cs new file mode 100644 index 00000000..5d819b5d --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/StatsdMetricsReporter.cs @@ -0,0 +1,54 @@ +using System.Collections.Generic; +using StatsdClient; + +namespace NPitaya.Metrics +{ + public class StatsdMetricsReporter: IMetricsReporter + { + public StatsdMetricsReporter(string statsdHost, int statsdPort, string metricsPrefix, Dictionary constantTags = null) + { + var parsedTags = _dictTagsToStringSlice(constantTags); + StatsdConfig statsdConfig = new StatsdConfig + { + StatsdServerName = statsdHost, + StatsdPort = statsdPort, + Prefix = metricsPrefix.TrimEnd('.'), + ConstantTags = parsedTags + }; + DogStatsd.Configure(statsdConfig); + } + + private static string[] _dictTagsToStringSlice(Dictionary dictTags) + { + if (dictTags is null) + { + return new string[0]; + } + var res = new string[dictTags.Count]; + var i = 0; + foreach (KeyValuePair kv in dictTags) + { + res[i++] = $"{kv.Key}:{kv.Value}"; + } + + return res; + } + + public void ReportCount(string metricKey, Dictionary tags, double value) + { + var parsedTags = _dictTagsToStringSlice(tags); + DogStatsd.Counter(metricKey, value, tags:parsedTags); + } + + public void ReportGauge(string metricKey, Dictionary tags, double value) + { + var parsedTags = _dictTagsToStringSlice(tags); + DogStatsd.Gauge(metricKey, value, tags:parsedTags); + } + public void ReportSummary(string metricKey, Dictionary tags, double value) + { + var parsedTags = _dictTagsToStringSlice(tags); + DogStatsd.Timer(metricKey, value, tags:parsedTags); + } + } +} \ No newline at end of file diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/StatsdMetricsReporter.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/StatsdMetricsReporter.cs.meta new file mode 100644 index 00000000..c75866ed --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Metrics/StatsdMetricsReporter.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9d5c39468625e8a47b28e6e46b1ced7c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Models.meta new file mode 100644 index 00000000..66d80e69 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 84b866563fc39d64da55cfefc243e127 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseHandler.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseHandler.cs new file mode 100644 index 00000000..e3763e93 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseHandler.cs @@ -0,0 +1,55 @@ +using System.Reflection; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace NPitaya.Models +{ + public class BaseHandler : IRemote + { + public string GetName() + { + return GetType().Name; + } + + public Dictionary GetRemotesMap() + { + Dictionary dict = new Dictionary(); + MethodBase[] methods = this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public); + foreach (var methodBase in methods) + { + var m = (MethodInfo) methodBase; + if (m.IsPublic) + { + if (typeof(Task).IsAssignableFrom(m.ReturnType)) + { + var returnType = m.ReturnType.GenericTypeArguments.Length > 0 + ? m.ReturnType.GenericTypeArguments[0] + : typeof(void); + ParameterInfo[] parameters = m.GetParameters(); + if (parameters.Length == 2) // TODO need to use context + { + if (typeof(PitayaSession) == + parameters[0].ParameterType && // TODO support bytes in and out, support context + (typeof(object).IsAssignableFrom(parameters[1].ParameterType))) + { + dict[m.Name] = new RemoteMethod(this, m, returnType, parameters[1].ParameterType); + } + } + + if (parameters.Length == 1 && typeof(PitayaSession) == parameters[0].ParameterType) + { + dict[m.Name] = new RemoteMethod(this, m, returnType, null); + } + } + } + } + + return dict; + } + + private static bool isValidHandler() + { + return true; //TODO implement this + } + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseHandler.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseHandler.cs.meta new file mode 100644 index 00000000..0c989b25 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseHandler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3417191c2a9f28b4aa642ac18b731736 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseRemote.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseRemote.cs new file mode 100644 index 00000000..30bdf438 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseRemote.cs @@ -0,0 +1,50 @@ +using System.Reflection; +using Google.Protobuf; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace NPitaya.Models +{ + public class BaseRemote : IRemote + { + public string GetName() + { + return GetType().Name; + } + + public Dictionary GetRemotesMap() + { + Dictionary dict = new Dictionary(); + MethodBase[] methods = GetType().GetMethods(BindingFlags.Instance | + BindingFlags.Public); + foreach (MethodInfo m in methods) + { + if (m.IsPublic) + { + if (typeof(Task).IsAssignableFrom(m.ReturnType)) + { + var returnType = m.ReturnType.GenericTypeArguments.Length > 0 + ? m.ReturnType.GenericTypeArguments[0] + : typeof(void); + ParameterInfo[] parameters = m.GetParameters(); + if (parameters.Length == 1) + { + if (typeof(object).IsAssignableFrom(parameters[0].ParameterType)) + { + dict[m.Name] = new RemoteMethod(this, m, returnType, + parameters[0].ParameterType); + } + } + } + } + } + + return dict; + } + + private static bool isValidRemote() + { + return true; + } + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseRemote.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseRemote.cs.meta new file mode 100644 index 00000000..03a0b734 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/BaseRemote.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e222ebd2923861c4c9ddb69f4612bdf8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/IRemote.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/IRemote.cs new file mode 100644 index 00000000..4c6b6831 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/IRemote.cs @@ -0,0 +1,11 @@ +using System.Collections.Generic; +using NPitaya; + +namespace NPitaya.Models +{ + public interface IRemote + { + string GetName(); + Dictionary GetRemotesMap(); + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/IRemote.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/IRemote.cs.meta new file mode 100644 index 00000000..2c75f32b --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/IRemote.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c2c439651197d8b438f8ee867efd4e29 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Logger.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Logger.cs new file mode 100644 index 00000000..11dbef17 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Logger.cs @@ -0,0 +1,49 @@ +using System; + +namespace NPitaya.Models{ + public enum LogLevel{ + ERROR=0, + WARNING=1, + INFO=2, + DEBUG=3 + } + + public static class Logger{ + private static LogLevel level = LogLevel.INFO; + public delegate void LogDelegate(LogLevel level, string logMsg, params object[] modifiers); + public static LogDelegate LogFunc = new LogDelegate(log); + + private static void log(LogLevel logLevel, string logMsg, params object[] modifiers){ + if (level >= logLevel){ + #if UNITY_STANDALONE || UNITY_EDITOR + UnityEngine.Debug.Log("[" + logLevel.ToString().ToUpper() + "] " + logMsg); + #else + Console.WriteLine("[" + logLevel.ToString().ToUpper() + "] " + logMsg, modifiers); + #endif + } + } + + public static void SetLevel(LogLevel logLevel){ + level = logLevel; + } + + public static void Error(string logMsg, params object[] modifiers){ + LogFunc(LogLevel.ERROR, logMsg, modifiers); + } + + public static void Warn(string logMsg, params object[] modifiers) + { + LogFunc(LogLevel.WARNING, logMsg, modifiers); + } + public static void Info(string logMsg, params object[] modifiers) + { + LogFunc(LogLevel.INFO, logMsg, modifiers); + } + + public static void Debug(string logMsg, params object[] modifiers) + { + LogFunc(LogLevel.DEBUG, logMsg, modifiers); + } + + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Logger.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Logger.cs.meta new file mode 100644 index 00000000..5452e4ed --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Logger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e2a52274ad0593b40b313084f79433b4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaConfiguration.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaConfiguration.cs new file mode 100644 index 00000000..ecc222c0 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaConfiguration.cs @@ -0,0 +1,98 @@ +using System.Collections.Generic; + + +namespace NPitaya.Models +{ + public class PitayaConfiguration + { + public const string CONFIG_HEARTBEAT_TIMEOUT_MS = "pitaya.sidecar.heartbeattimeoutms"; + public const string CONFIG_READBUFFER_SIZE = "pitaya.sidecar.readbuffersize"; + public const string CONFIG_WRITEBUFFER_SIZE = "pitaya.sidecar.writebuffersize"; + + public static Dictionary DefaultValues = new Dictionary{ + {CONFIG_HEARTBEAT_TIMEOUT_MS, 5000}, + {CONFIG_READBUFFER_SIZE, 1000}, + {CONFIG_WRITEBUFFER_SIZE, 1000}, + }; + + public Dictionary defaultValues; + private readonly Dictionary configMap = new Dictionary(); + + public static PitayaConfiguration Config; + + private void initializeDefaultConfigurations(){ + foreach (var kv in defaultValues){ + configMap[kv.Key] = kv.Value; + } + } + + private string configNameToEnvVar(string configName){ + return configName.ToUpper().Replace(".", "_"); + } + + private void replaceConfigWithEnv(){ + foreach (var kv in defaultValues) + { + var envVarValue = System.Environment.GetEnvironmentVariable(configNameToEnvVar(kv.Key)); + if (envVarValue != null){ + if(int.TryParse(kv.Value.ToString(), out var intVal)){ + if (int.TryParse(envVarValue, out var ret)){ + configMap[kv.Key] = ret; + } else { + Logger.Error("Tried to set int configuration: {0} with non valid number: {1}", kv.Key, envVarValue); + } + } else { + configMap[kv.Key] = envVarValue; + } + } + } + } + + static PitayaConfiguration() { + if (Config == null){ + Config = new PitayaConfiguration(); + } + } + + public PitayaConfiguration(Dictionary defaultValues){ + this.defaultValues = defaultValues; + initializeDefaultConfigurations(); + replaceConfigWithEnv(); + } + + public PitayaConfiguration(){ + defaultValues = DefaultValues; + initializeDefaultConfigurations(); + replaceConfigWithEnv(); + } + + public string getString(string key){ + return configMap[key].ToString(); + } + + public object get(string key){ + return configMap[key]; + } + + public int getInt(string key){ + int.TryParse(configMap[key].ToString(), out var ret); + return ret; + } + + public void putInt(string key, int value){ + configMap[key] = value; + } + + public void putString(string key, string value){ + configMap[key] = value; + } + + public void reset(){ + configMap.Clear(); + initializeDefaultConfigurations(); + replaceConfigWithEnv(); + } + + } + +} \ No newline at end of file diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaConfiguration.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaConfiguration.cs.meta new file mode 100644 index 00000000..27d666a1 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaConfiguration.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f31a5238be9b2ed42850427e3a4a5bd4 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaSession.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaSession.cs new file mode 100644 index 00000000..d7c921f8 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaSession.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Google.Protobuf; +using NPitaya.Constants; +using Json = PitayaSimpleJson.SimpleJson; +using NPitaya.Protos; + +namespace NPitaya.Models +{ + public class PitayaSession + { + private Int64 _id; + private string _frontendId; + private Dictionary _data; + private string _rawData; + public string RawData => _rawData; + public string Uid { get; private set; } + + public PitayaSession(Protos.Session sessionProto) + { + _id = sessionProto.Id; + Uid = sessionProto.Uid; + _rawData = sessionProto.Data.ToStringUtf8(); + if (!String.IsNullOrEmpty(_rawData)) + _data = Json.DeserializeObject>(_rawData); + } + + public PitayaSession(Protos.Session sessionProto, string frontendId):this(sessionProto) + { + _frontendId = frontendId; + } + + public override string ToString() + { + return $"ID: {_id}, UID: {Uid}, Data: {_rawData}"; + } + + public void Set(string key, object value) + { + _data[key] = value; + _rawData = Json.SerializeObject(_data); + } + + public object GetObject(string key) + { + if (!_data.ContainsKey(key)) + { + throw new Exception($"key not found in session, parameter: {key}"); + } + + return _data[key]; + } + + public string GetString(string key) + { + return GetObject(key) as string; + } + + public int GetInt(string key) + { + var obj = GetObject(key); + return obj is int ? (int) obj : 0; + } + + public double GetDouble(string key) + { + var obj = GetObject(key); + return obj is double ? (double) obj : 0; + } + + public Task PushToFrontend() + { + if (String.IsNullOrEmpty(_frontendId)) + { + return Task.FromException(new Exception("cannot push to frontend, frontendId is invalid!")); + } + return SendRequestToFront(Routes.SessionPushRoute, true); + } + + public Task Bind(string uid) + { + if (Uid != "") + { + return Task.FromException(new Exception("session already bound!")); + } + Uid = uid; + // TODO only if server type is backend + // TODO bind callbacks + if (!string.IsNullOrEmpty(_frontendId)){ + return BindInFrontend(); + } + + return Task.CompletedTask; + } + + private Task BindInFrontend() + { + return SendRequestToFront(Routes.SessionBindRoute, false); + } + + private Task SendRequestToFront(string route, bool includeData) + { + var sessionProto = new Protos.Session + { + Id = _id, + Uid = Uid + }; + if (includeData) + { + sessionProto.Data = ByteString.CopyFromUtf8(_rawData); + } + return PitayaCluster.Rpc(_frontendId, Route.FromString(route), sessionProto.ToByteArray()); + } + + public Task Push(object pushMsg, string svType, string route) + { + return PitayaCluster.SendPushToUser(svType, route, Uid, pushMsg); + } + + public Task Kick(string svType) + { + return PitayaCluster.SendKickToUser(svType, new KickMsg + { + UserId = Uid + }); + } + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaSession.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaSession.cs.meta new file mode 100644 index 00000000..6ad79c4f --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/PitayaSession.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c77d51e32d381104cb1b7aa5d11100a2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Remote.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Remote.cs new file mode 100644 index 00000000..546ed4bc --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Remote.cs @@ -0,0 +1,18 @@ +namespace NPitaya.Models +{ + [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct)] + public class Remote: System.Attribute + { + private string _name; + + public Remote(string name) + { + _name = name; + } + + public Remote() + { + _name = Utils.Utils.DefaultRemoteNameFunc(GetType().Name); + } + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Remote.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Remote.cs.meta new file mode 100644 index 00000000..683c123e --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/Remote.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0d767fd7ea714cd40a46022c7a328cb9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/RemoteMethod.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/RemoteMethod.cs new file mode 100644 index 00000000..a4f549e0 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/RemoteMethod.cs @@ -0,0 +1,19 @@ +using System; +using System.Reflection; + +namespace NPitaya.Models +{ + public class RemoteMethod + { + public readonly IRemote Obj; + internal MethodBase Method { get; } + internal Type ReturnType { get; } + internal Type ArgType { get; } + public RemoteMethod(IRemote obj, MethodBase method, Type returnType, Type argType){ + Obj = obj; + Method = method; + ReturnType = returnType; + ArgType = argType; + } + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Models/RemoteMethod.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/RemoteMethod.cs.meta new file mode 100644 index 00000000..a20929ee --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Models/RemoteMethod.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2794e4dcdeead1a4ebbe36c7b54cacc3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/NativeInterop.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/NativeInterop.cs new file mode 100644 index 00000000..742bf06d --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/NativeInterop.cs @@ -0,0 +1,218 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using PitayaSimpleJson; + +namespace NPitaya +{ + + [StructLayout(LayoutKind.Sequential)] + public struct CRpc + { + public IntPtr reqBufferPtr; + public IntPtr tag; + } + + [StructLayout(LayoutKind.Sequential)] + public struct Error + { + [MarshalAs(UnmanagedType.LPStr)] + public string code; + [MarshalAs(UnmanagedType.LPStr)] + public string msg; + } + + public enum NativeLogLevel + { + Debug = 0, + Info = 1, + Warn = 2, + Error = 3, + Critical = 4, + } + + [StructLayout(LayoutKind.Sequential)] + public struct SDConfig + { + [MarshalAs(UnmanagedType.LPStr)] + public string endpoints; + [MarshalAs(UnmanagedType.LPStr)] + public string etcdPrefix; + [MarshalAs(UnmanagedType.LPStr)] + public string serverTypeFiltersStr; + public int heartbeatTTLSec; + public int logHeartbeat; + public int logServerSync; + public int logServerDetails; + public int syncServersIntervalSec; + public int maxNumberOfRetries; + + public SDConfig(string endpoints, string etcdPrefix, List serverTypeFilters, int heartbeatTTLSec, bool logHeartbeat, + bool logServerSync, bool logServerDetails, int syncServersIntervalSec, int maxNumberOfRetries) + { + this.endpoints = endpoints; + this.etcdPrefix = etcdPrefix; + this.heartbeatTTLSec = heartbeatTTLSec; + this.logHeartbeat = Convert.ToInt32(logHeartbeat); + this.logServerSync = Convert.ToInt32(logServerSync); + this.logServerDetails = Convert.ToInt32(logServerDetails); + this.syncServersIntervalSec = syncServersIntervalSec; + this.maxNumberOfRetries = maxNumberOfRetries; + try + { + serverTypeFiltersStr = SimpleJson.SerializeObject(serverTypeFilters); + } + catch (Exception e) + { + throw new Exception("Failed to serialize serverTypeFilters: " + e.Message); + } + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct GrpcConfig + { + [MarshalAs(UnmanagedType.LPStr)] + public string host; + public int port; + public int serverShutdownDeadlineMs; + public int serverMaxNumberOfRpcs; + public int clientRpcTimeoutMs; + + public GrpcConfig( + string host, + int port, + int serverShutdownDeadlineMs, + int serverMaxNumberOfRpcs, + int clientRpcTimeoutMs) + { + this.host = host; + this.port = port; + this.serverShutdownDeadlineMs = serverShutdownDeadlineMs; + this.serverMaxNumberOfRpcs = serverMaxNumberOfRpcs; + this.clientRpcTimeoutMs = clientRpcTimeoutMs; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct Route + { + [MarshalAs(UnmanagedType.LPStr)] + public string svType; + [MarshalAs(UnmanagedType.LPStr)] + public string service; + [MarshalAs(UnmanagedType.LPStr)] + public string method; + + public Route(string svType, string service, string method):this(service, method) + { + this.svType = svType; + } + + public Route(string service, string method) + { + this.service = service; + this.method = method; + svType = ""; + } + + public static Route FromString(string r) + { + string[] res = r.Split(new[] { "." }, StringSplitOptions.None); + if (res.Length == 3) + { + return new Route(res[0], res[1], res[2]); + } + if (res.Length == 2) + { + return new Route(res[0], res[1]); + } + throw new Exception($"invalid route: {r}"); + } + + public override string ToString() + { + if (svType.Length > 0) + { + return $"{svType}.{service}.{method}"; + } + return $"{service}.{method}"; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct MemoryBuffer + { + public IntPtr data; + public int size; + + public byte[] GetData() + { + byte[] data = new byte[this.size]; + Marshal.Copy(this.data, data, 0, this.size); + return data; + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct NatsConfig + { + [MarshalAs(UnmanagedType.LPStr)] + public string endpoint; + public Int64 connectionTimeoutMs; + public int requestTimeoutMs; + public int serverShutdownDeadlineMs; + public int serverMaxNumberOfRpcs; + public int maxConnectionRetries; + public int maxPendingMessages; + + public NatsConfig(string endpoint, + int connectionTimeoutMs, + int requestTimeoutMs, + int serverShutdownDeadlineMs, + int serverMaxNumberOfRpcs, + int maxConnectionRetries, + int maxPendingMessages) + { + this.endpoint = endpoint; + this.connectionTimeoutMs = connectionTimeoutMs; + this.requestTimeoutMs = requestTimeoutMs; + this.serverShutdownDeadlineMs = serverShutdownDeadlineMs; + this.serverMaxNumberOfRpcs = serverMaxNumberOfRpcs; + this.maxConnectionRetries = maxConnectionRetries; + this.maxPendingMessages = maxPendingMessages; + } + } +} + +class StructWrapper : IDisposable +{ + public IntPtr Ptr { get; private set; } + + public StructWrapper(object obj) + { + Ptr = Marshal.AllocHGlobal(Marshal.SizeOf(obj)); + Marshal.StructureToPtr(obj, Ptr, false); + } + + ~StructWrapper() + { + if (Ptr != IntPtr.Zero) + { + Marshal.FreeHGlobal(Ptr); + Ptr = IntPtr.Zero; + } + } + + public void Dispose() + { + Marshal.FreeHGlobal(Ptr); + Ptr = IntPtr.Zero; + GC.SuppressFinalize(this); + } + + public static implicit operator IntPtr(StructWrapper w) + { + return w.Ptr; + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/NativeInterop.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/NativeInterop.cs.meta new file mode 100644 index 00000000..09352357 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/NativeInterop.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d2a0a44a99e3a8740814bdcb41ac4a22 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/PSidecarClient.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/PSidecarClient.cs new file mode 100644 index 00000000..2816cf2e --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/PSidecarClient.cs @@ -0,0 +1,81 @@ +using System; +using Grpc.Core; +using NPitaya.Models; +using NPitaya.Protos; +using System.Threading.Tasks; + +namespace NPitaya +{ + public partial class PitayaCluster + { + private static bool _isInitialized = false; + private static Sidecar.SidecarClient _client = null; + private static Grpc.Core.Channel _channel; + + static PitayaCluster(){ + GrpcEnvironment.SetCompletionQueueCount(Environment.ProcessorCount); + GrpcEnvironment.SetThreadPoolSize(Environment.ProcessorCount); + } + + public static void InitializeSidecarClient(string sidecarAddr, int sidecarPort, NPitaya.Protos.Server server, bool debug = false) + { + if (_isInitialized) + { + Logger.Warn("Pitaya is already initialized!"); + return; + } + + if (sidecarPort != 0) + { + _channel = new Channel(sidecarAddr, sidecarPort, ChannelCredentials.Insecure); + } + else + { + _channel = new Channel(sidecarAddr, ChannelCredentials.Insecure); + } + + _client = new Sidecar.SidecarClient(_channel); + var req = new StartPitayaRequest { Config = server, DebugLog = debug }; + + _client.StartPitaya(req); + // this is a hacky approach to detect if server is not running anymore, and if not, die + new System.Threading.Thread(async() => + { + while (!_channel.ShutdownToken.IsCancellationRequested) + { + _client.Heartbeat(new Google.Protobuf.WellKnownTypes.Empty()); + var timeoutMs = PitayaConfiguration.Config.getInt(PitayaConfiguration.CONFIG_HEARTBEAT_TIMEOUT_MS); + await Task.Delay(TimeSpan.FromMilliseconds(timeoutMs), + _channel.ShutdownToken); + } + }).Start(); + _isInitialized = true; + } + public static void InitializeSidecarClient(string sidecarSocketAddr, NPitaya.Protos.Server server, bool debug = false) + { + InitializeSidecarClient(sidecarSocketAddr, 0, server, debug); + } + + public static void ShutdownSidecar(){ + if (!_isInitialized){ + return; + } + var task = _channel.ShutdownAsync(); + task.Wait(); + _client = null; + _channel = null; + _isInitialized = false; + } + public static async Task ShutdownSidecarAsync() + { + if (!_isInitialized) { + return false; + } + await _channel.ShutdownAsync(); + _channel = null; + _client = null; + _isInitialized = false; + return true; + } + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/PSidecarClient.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/PSidecarClient.cs.meta new file mode 100644 index 00000000..96efa61a --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/PSidecarClient.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: dca4e6707051534468c19e085fcf97e6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.API.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.API.cs new file mode 100644 index 00000000..9fbd2fa3 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.API.cs @@ -0,0 +1,333 @@ +using System; +using Google.Protobuf; +using System.Collections.Generic; +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +using NPitaya.Metrics; +using NPitaya.Models; +using NPitaya.Serializer; +using NPitaya.Protos; +using NPitaya.Utils; +using static NPitaya.Utils.Utils; +using System.Linq; + +// TODO profiling +// TODO better reflection performance in task async call +// TODO support to sync methods +// TODO benchmark with blocking handlers +namespace NPitaya +{ + public partial class PitayaCluster + { + private static readonly int ProcessorsCount = Environment.ProcessorCount; + private static ISerializer _serializer = new ProtobufSerializer(); + public delegate string RemoteNameFunc(string methodName); + private delegate void OnSignalFunc(); + private static readonly Dictionary RemotesDict = new Dictionary(); + private static readonly Dictionary HandlersDict = new Dictionary(); + private static readonly LimitedConcurrencyLevelTaskScheduler Lcts = new LimitedConcurrencyLevelTaskScheduler(ProcessorsCount); + private static TaskFactory _rpcTaskFactory = new TaskFactory(Lcts); + + private static Action _onSignalEvent; + private static bool _processedSigint = false; + + private static Action _onSDEvent; + + // Sidecar stuff + + static BlockingCollection queueRead = new BlockingCollection(PitayaConfiguration.Config.getInt(PitayaConfiguration.CONFIG_READBUFFER_SIZE)); + static BlockingCollection queueWrite = new BlockingCollection(PitayaConfiguration.Config.getInt(PitayaConfiguration.CONFIG_WRITEBUFFER_SIZE)); + + public static void AddSignalHandler(Action cb) + { + _onSignalEvent += cb; + } + + private static void OnSignal() + { + Logger.Info("Invoking signal handler"); + _onSignalEvent?.Invoke(); + } + + private static List GetAllInheriting(Type type) + { + return AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()) + .Where(x => type.IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract && x.FullName != type.FullName) + .Select(x => x).ToList(); + } + + private static void ListenSDEvents(Sidecar.SidecarClient client) + { + var stream = client.ListenSD(new Google.Protobuf.WellKnownTypes.Empty()); + new Thread(async () =>{ + while (await stream.ResponseStream.MoveNext(_channel.ShutdownToken)) + { + var current = stream.ResponseStream.Current; + if (_onSDEvent != null){ + _onSDEvent(current); + } + } + }).Start(); + } + + private static void ListenToIncomingRPCs(Sidecar.SidecarClient client) + { + var stream = client.ListenRPC(); + + new Thread(async () =>{ + while (await stream.ResponseStream.MoveNext(_channel.ShutdownToken)) + { + var current = stream.ResponseStream.Current; + queueRead.Add(current); + } + }).Start(); + + new Thread(async () =>{ + while (true) + { + var res = queueWrite.Take(); + await stream.RequestStream.WriteAsync(res); + } + }).Start(); + + for (int i = 0; i < ProcessorsCount; i++) + { + var threadId = i + 1; + new Thread(async () => + { + Logger.Debug($"[Consumer thread {threadId}] Started"); + while (!_channel.ShutdownToken.IsCancellationRequested) + { + var req = queueRead.Take(_channel.ShutdownToken); + //#pragma warning disable 4014 + var res = await HandleIncomingRpc(req.Req); + //#pragma warning restore 4014 + queueWrite.Add(new Protos.RPCResponse { ReqId = req.ReqId, Res = res }); + } + }).Start(); + } + } + + private static void RegisterRemotesAndHandlers(){ + var handlers = GetAllInheriting(typeof(BaseHandler)); + foreach (var handler in handlers){ + RegisterHandler((BaseHandler)Activator.CreateInstance(handler)); + } + + var remotes = GetAllInheriting(typeof(BaseRemote)); + foreach (var remote in remotes){ + RegisterRemote((BaseRemote)Activator.CreateInstance(remote)); + } + } + + public static void Initialize( + string sidecarListenAddr, + int sidecarPort, + Server server, + bool debug, + Action cbServiceDiscovery = null + ) + { + if (_isInitialized){ + Logger.Warn("Initialize called but pitaya is already initialized"); + return; + } + InitializeSidecarClient(sidecarListenAddr, sidecarPort, server, debug); + + if (_client == null) + { + throw new PitayaException("Initialization failed"); + } + + RegisterRemotesAndHandlers(); + + ListenToIncomingRPCs(_client); + SetServiceDiscoveryListener(cbServiceDiscovery); + ListenSDEvents(_client); + RegisterGracefulShutdown(); + } + + private static void RegisterGracefulShutdown(){ + Console.CancelKeyPress += (_, ea) => + { + _processedSigint = true; + Console.WriteLine("Received SIGINT (Ctrl+C), executing on signal function"); + OnSignal(); + Terminate(); + }; + + AppDomain.CurrentDomain.ProcessExit += (_, ea) => + { + if (_processedSigint) { + Console.WriteLine("Ignoring SIGTERM, already processed SIGINT"); + } else{ + Console.WriteLine("Received SIGTERM, executing on signal function"); + OnSignal(); + Terminate(); + } + }; + } + + private static void RegisterRemote(BaseRemote remote) + { + string className = DefaultRemoteNameFunc(remote.GetName()); + RegisterRemote(remote, className, DefaultRemoteNameFunc); + } + + private static void RegisterRemote(BaseRemote remote, string name, RemoteNameFunc remoteNameFunc) + { + Dictionary m = remote.GetRemotesMap(); + foreach (KeyValuePair kvp in m) + { + var rn = remoteNameFunc(kvp.Key); + var remoteName = $"{name}.{rn}"; + if (RemotesDict.ContainsKey(remoteName)) + { + throw new PitayaException($"tried to register same remote twice! remote name: {remoteName}"); + } + + Logger.Info("registering remote {0}", remoteName); + RemotesDict[remoteName] = kvp.Value; + } + } + + private static void RegisterHandler(BaseHandler handler) + { + string className = DefaultRemoteNameFunc(handler.GetName()); + RegisterHandler(handler, className, DefaultRemoteNameFunc); + } + + public static void RegisterHandler(BaseHandler handler, string name, RemoteNameFunc remoteNameFunc) + { + Dictionary m = handler.GetRemotesMap(); + foreach (KeyValuePair kvp in m) + { + var rn = remoteNameFunc(kvp.Key); + var handlerName = $"{name}.{rn}"; + if (HandlersDict.ContainsKey(handlerName)) + { + throw new PitayaException($"tried to register same remote twice! remote name: {handlerName}"); + } + + Logger.Info("registering handler {0}", handlerName); + HandlersDict[handlerName] = kvp.Value; + } + } + + public static void SetSerializer(ISerializer s) + { + _serializer = s; + } + public static void Terminate() + { + if (_isInitialized){ + UnsetServiceDiscoveryListener(); + _client.StopPitaya(new Google.Protobuf.WellKnownTypes.Empty()); + ShutdownSidecar(); + } + } + + public static async void TerminateAsync() + { + if (_isInitialized){ + UnsetServiceDiscoveryListener(); + await _client.StopPitayaAsync(new Google.Protobuf.WellKnownTypes.Empty()); + await ShutdownSidecarAsync(); + } + } + + public static Server GetServerById(string serverId) + { + try{ + var protoSv = _client.GetServer(new NPitaya.Protos.Server{Id=serverId}); + return protoSv; + } catch (Exception){ + return null; + } + } + + // TODO deprecate this frontendId field, it's not useful when using nats + public static Task SendPushToUser(string serverType, string route, string uid, + object pushMsg) + { + // TODO see if this taskfactory is still required + return _rpcTaskFactory.StartNew(() => + { + var push = new Push + { + Route = route, + Uid = uid, + Data = ByteString.CopyFrom(SerializerUtils.SerializeOrRaw(pushMsg, _serializer)) + }; + + return _client.SendPush(new PushRequest{FrontendType=serverType, Push=push}); + }); + } + + public static Task SendKickToUser(string serverType, KickMsg kick) + { + return _rpcTaskFactory.StartNew(() => + { + return _client.SendKick(new KickRequest{FrontendType=serverType, Kick=kick}); + }); + } + + public static Task Rpc(string serverId, Route route, object msg) + { + return _rpcTaskFactory.StartNew(() => + { + var retError = new Error(); + var ok = false; + Response res = null; + Stopwatch sw = null; + try + { + var data = SerializerUtils.SerializeOrRaw(msg, _serializer); + sw = Stopwatch.StartNew(); + // TODO this can be optimized I think by using a readonly span + res = _client.SendRPC(new RequestTo{ServerID=serverId, Msg=new Msg{Route=route.ToString(), Data=ByteString.CopyFrom(data.AsSpan()), Type=MsgType.MsgRequest}}); + + sw.Stop(); + var protoRet = GetProtoMessageFromResponse(res); + return protoRet; + } + finally + { + if (sw != null) + { + if (ok) + { + MetricsReporters.ReportTimer(Metrics.Constants.Status.success.ToString(), route.ToString(), + "rpc", "", sw); + } + else + { + MetricsReporters.ReportTimer(Metrics.Constants.Status.fail.ToString(), route.ToString(), + "rpc", $"{retError.code}", sw); + } + } + } + }); + } + + public static Task Rpc(Route route, object msg) + { + return Rpc("", route, msg); + } + + private static void SetServiceDiscoveryListener(Action cb) + { + _onSDEvent += cb; + } + + private static void UnsetServiceDiscoveryListener() + { + if (_onSDEvent != null) + { + _onSDEvent = null; + } + } + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.API.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.API.cs.meta new file mode 100644 index 00000000..6f3e79c9 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.API.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c032f1bb071d25b4592dc73effd2f2cc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.RPC.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.RPC.cs new file mode 100644 index 00000000..04d4ebc7 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.RPC.cs @@ -0,0 +1,156 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Google.Protobuf; +using NPitaya.Metrics; +using NPitaya.Models; +using NPitaya.Serializer; +using NPitaya.Protos; +using static NPitaya.Utils.Utils; + +namespace NPitaya +{ + public partial class PitayaCluster + { + private static async Task HandleIncomingRpc(Request req) + { + Response res = null; + String route = req.Msg.Route; + bool success = false; + var sw = Stopwatch.StartNew(); + try{ + res = await RPCCbFuncImpl(req, sw); + success = true; + return res; + } + catch (Exception e) + { + var innerMostException = e; + while (innerMostException.InnerException != null) + innerMostException = innerMostException.InnerException; + + Logger.Error("Exception thrown in handler, error:{0}", + innerMostException.Message); // TODO externalize method and only print stacktrace when debug +#if NPITAYA_DEBUG + // If we are compiling with a Debug define, we want to print a stacktrace whenever a route + // throws an exception. + Logger.Error("Stacktrace: {0}", innerMostException.StackTrace); +#endif + res = GetErrorResponse("PIT-500", innerMostException.Message); + return res; + } + finally + { + if (success) + { + MetricsReporters.ReportTimer(Metrics.Constants.Status.success.ToString(), route, + "handler", "", sw); + } + else + { + MetricsReporters.ReportTimer(Metrics.Constants.Status.fail.ToString(), route, + "handler", "PIT-500", sw); + } + } + } + + //private static Request BuildRequestData(IntPtr reqBufferPtr) + //{ + // var reqBuffer = (MemoryBuffer) Marshal.PtrToStructure(reqBufferPtr, typeof(MemoryBuffer)); + + // Request req = new Request(); + // req.MergeFrom(new CodedInputStream(reqBuffer.GetData())); + // return req; + //} + + private static async Task RPCCbFuncImpl(Request req, Stopwatch sw) + { + Response response; + switch (req.Type) + { + case RPCType.User: + response = await HandleRpc(req, RPCType.User, sw); + break; + case RPCType.Sys: + response = await HandleRpc(req, RPCType.Sys, sw); + break; + default: + throw new Exception($"invalid rpc type, argument:{req.Type}"); + } + + return response; + } + + internal static async Task HandleRpc(Protos.Request req, RPCType type, Stopwatch sw) + { + byte[] data = req.Msg.Data.ToByteArray(); + Route route = Route.FromString(req.Msg.Route); + + string handlerName = $"{route.service}.{route.method}"; + + PitayaSession s = null; + var response = new Response(); + + RemoteMethod handler; + if (type == RPCType.Sys) + { + s = new Models.PitayaSession(req.Session, req.FrontendID); + if (!HandlersDict.ContainsKey(handlerName)) + { + response = GetErrorResponse("PIT-404", + $"remote/handler not found! remote/handler name: {handlerName}"); + return response; + } + + handler = HandlersDict[handlerName]; + MetricsReporters.ReportMessageProccessDelay(req.Msg.Route,"local", sw); + } + else + { + if (!RemotesDict.ContainsKey(handlerName)) + { + response = GetErrorResponse("PIT-404", + $"remote/handler not found! remote/handler name: {handlerName}"); + return response; + } + + handler = RemotesDict[handlerName]; + MetricsReporters.ReportMessageProccessDelay(req.Msg.Route,"remote", sw); + } + + Task ans; + if (handler.ArgType != null) + { + var arg = _serializer.Unmarshal(data, handler.ArgType); + if (type == RPCType.Sys) + ans = handler.Method.Invoke(handler.Obj, new[] {s, arg}) as Task; + else + ans = handler.Method.Invoke(handler.Obj, new[] {arg}) as Task; + } + else + { + if (type == RPCType.Sys) + ans = handler.Method.Invoke(handler.Obj, new object[] {s}) as Task; + else + ans = handler.Method.Invoke(handler.Obj, new object[] { }) as Task; + } + + await ans; + byte[] ansBytes; + + if (handler.ReturnType != typeof(void)) + { + ansBytes = SerializerUtils.SerializeOrRaw(ans.GetType(). + GetProperty("Result") + ?.GetValue(ans), _serializer); + } + else + { + ansBytes = new byte[]{}; + } + response.Data = ByteString.CopyFrom(ansBytes); + return response; + } + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.RPC.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.RPC.cs.meta new file mode 100644 index 00000000..40ed35a2 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaCluster.RPC.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e3355d57adcdad84a80dc63cc4c47bcb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaException.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaException.cs new file mode 100644 index 00000000..0f6c4827 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaException.cs @@ -0,0 +1,22 @@ +using System; + +namespace NPitaya +{ + public class PitayaException : Exception + { + public PitayaException() + : base() { } + + public PitayaException(string message) + : base(message) { } + + public PitayaException(string format, params object[] args) + : base(string.Format(format, args)) { } + + public PitayaException(string message, Exception innerException) + : base(message, innerException) { } + + public PitayaException(string format, Exception innerException, params object[] args) + : base(string.Format(format, args), innerException) { } + } +} \ No newline at end of file diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaException.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaException.cs.meta new file mode 100644 index 00000000..a3b97c67 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/PitayaException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2c3802c00655bbb48a3825e0dfa58522 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer.meta new file mode 100644 index 00000000..686bd51b --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a91d12a1f6f25e44180f996a5305e1e1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ISerializer.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ISerializer.cs new file mode 100644 index 00000000..63b05fa4 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ISerializer.cs @@ -0,0 +1,10 @@ +using System; + +namespace NPitaya.Serializer +{ + public interface ISerializer + { + byte[] Marshal(object o); + object Unmarshal(byte[] bytes, Type t); + } +} \ No newline at end of file diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ISerializer.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ISerializer.cs.meta new file mode 100644 index 00000000..228d31bc --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ISerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4d978843a17414542805c5aac6f02c48 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/JSONSerializer.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/JSONSerializer.cs new file mode 100644 index 00000000..97159908 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/JSONSerializer.cs @@ -0,0 +1,20 @@ +using System; +using System.Text; +using PitayaSimpleJson; + +namespace NPitaya.Serializer +{ + public class JSONSerializer: ISerializer + { + public byte[] Marshal(object o) + { + return Encoding.UTF8.GetBytes(PitayaSimpleJson.SimpleJson.SerializeObject(o)); + } + + public object Unmarshal(byte[] bytes, Type t) + { + if (bytes.Length == 0) bytes = Encoding.UTF8.GetBytes("{}"); + return PitayaSimpleJson.SimpleJson.DeserializeObject(Encoding.UTF8.GetString(bytes), t); + } + } +} \ No newline at end of file diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/JSONSerializer.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/JSONSerializer.cs.meta new file mode 100644 index 00000000..de120ba8 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/JSONSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 787e6dc9ff2061443a11f6a4b1bea7bc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ProtobufSerializer.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ProtobufSerializer.cs new file mode 100644 index 00000000..f1a45d56 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ProtobufSerializer.cs @@ -0,0 +1,33 @@ +using System; +using Google.Protobuf; + +namespace NPitaya.Serializer +{ + public class ProtobufSerializer: ISerializer + { + public byte[] Marshal(object o) + { + if (o == null) return new byte[]{}; + if (!(o is IMessage)) + { + throw new PitayaException("Cannot serialize a type that doesn't implement IMessage"); + } + + if (o == null) return new byte[] { }; + + return ((IMessage) o).ToByteArray(); + } + + public object Unmarshal(byte[] bytes, Type t) + { + if (!typeof(IMessage).IsAssignableFrom(t)) + { + throw new PitayaException("Cannot deserialize to a type that doesn't implement IMessage"); + + } + var res = Activator.CreateInstance(t); + ((IMessage)res).MergeFrom(bytes); + return res; + } + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ProtobufSerializer.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ProtobufSerializer.cs.meta new file mode 100644 index 00000000..2f28ca70 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/ProtobufSerializer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 814d56fea967a6a448b47356514a51de +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/SerializerUtils.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/SerializerUtils.cs new file mode 100644 index 00000000..41a1c0a4 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/SerializerUtils.cs @@ -0,0 +1,15 @@ +namespace NPitaya.Serializer +{ + public class SerializerUtils + { + public static byte[] SerializeOrRaw(object obj, ISerializer serializer) + { + if (obj is byte[]) + { + return (byte[])obj; + } + + return serializer.Marshal(obj); + } + } +} \ No newline at end of file diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/SerializerUtils.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/SerializerUtils.cs.meta new file mode 100644 index 00000000..0ed70755 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Serializer/SerializerUtils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7872235500e617e438d856766bc07c2d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Utils.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils.meta new file mode 100644 index 00000000..7f446620 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5171d3a59e9c78240a930d63385bcdc0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/LimitedConcurrencyLevelTaskScheduler.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/LimitedConcurrencyLevelTaskScheduler.cs new file mode 100644 index 00000000..1de69fd9 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/LimitedConcurrencyLevelTaskScheduler.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace NPitaya.Utils +{ + // Provides a task scheduler that ensures a maximum concurrency level while + // running on top of the thread pool. + public class LimitedConcurrencyLevelTaskScheduler : TaskScheduler + { + // Indicates whether the current thread is processing work items. + [ThreadStatic] + private static bool _currentThreadIsProcessingItems; + + // The list of tasks to be executed + private readonly LinkedList _tasks = new LinkedList(); // protected by lock(_tasks) + + // The maximum concurrency level allowed by this scheduler. + private readonly int _maxDegreeOfParallelism; + + // Indicates whether the scheduler is currently processing work items. + private int _delegatesQueuedOrRunning = 0; + + // Creates a new instance with the specified degree of parallelism. + public LimitedConcurrencyLevelTaskScheduler(int maxDegreeOfParallelism) + { + if (maxDegreeOfParallelism < 1) throw new ArgumentOutOfRangeException("maxDegreeOfParallelism"); + _maxDegreeOfParallelism = maxDegreeOfParallelism; + } + + // Queues a task to the scheduler. + protected sealed override void QueueTask(Task task) + { + // Add the task to the list of tasks to be processed. If there aren't enough + // delegates currently queued or running to process tasks, schedule another. + lock (_tasks) + { + _tasks.AddLast(task); + if (_delegatesQueuedOrRunning < _maxDegreeOfParallelism) + { + ++_delegatesQueuedOrRunning; + NotifyThreadPoolOfPendingWork(); + } + } + } + + // Inform the ThreadPool that there's work to be executed for this scheduler. + private void NotifyThreadPoolOfPendingWork() + { + ThreadPool.UnsafeQueueUserWorkItem(_ => + { + // Note that the current thread is now processing work items. + // This is necessary to enable inlining of tasks into this thread. + _currentThreadIsProcessingItems = true; + try + { + // Process all available items in the queue. + while (true) + { + Task item; + lock (_tasks) + { + // When there are no more items to be processed, + // note that we're done processing, and get out. + if (_tasks.Count == 0) + { + --_delegatesQueuedOrRunning; + break; + } + + // Get the next item from the queue + item = _tasks.First.Value; + _tasks.RemoveFirst(); + } + + // Execute the task we pulled out of the queue + base.TryExecuteTask(item); + } + } + // We're done processing items on the current thread + finally { _currentThreadIsProcessingItems = false; } + }, null); + } + + // Attempts to execute the specified task on the current thread. + protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) + { + // If this thread isn't already processing a task, we don't support inlining + if (!_currentThreadIsProcessingItems) return false; + + // If the task was previously queued, remove it from the queue + if (taskWasPreviouslyQueued) + // Try to run the task. + if (TryDequeue(task)) + return base.TryExecuteTask(task); + else + return false; + else + return base.TryExecuteTask(task); + } + + // Attempt to remove a previously scheduled task from the scheduler. + protected sealed override bool TryDequeue(Task task) + { + lock (_tasks) return _tasks.Remove(task); + } + + // Gets the maximum concurrency level supported by this scheduler. + public sealed override int MaximumConcurrencyLevel { get { return _maxDegreeOfParallelism; } } + + // Gets an enumerable of the tasks currently scheduled on this scheduler. + protected sealed override IEnumerable GetScheduledTasks() + { + bool lockTaken = false; + try + { + Monitor.TryEnter(_tasks, ref lockTaken); + if (lockTaken) return _tasks; + else throw new NotSupportedException(); + } + finally + { + if (lockTaken) Monitor.Exit(_tasks); + } + } + } +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/LimitedConcurrencyLevelTaskScheduler.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/LimitedConcurrencyLevelTaskScheduler.cs.meta new file mode 100644 index 00000000..d8a49c2a --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/LimitedConcurrencyLevelTaskScheduler.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 83362c1778bde7e4ba999a8cf412afcf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/PitayaSimpleJson.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/PitayaSimpleJson.cs new file mode 100644 index 00000000..2df3a450 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/PitayaSimpleJson.cs @@ -0,0 +1,1936 @@ +//----------------------------------------------------------------------- +// +// Copyright (c) 2011, The Outercurve Foundation. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.opensource.org/licenses/mit-license.php +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me) +// https://github.com/facebook-csharp-sdk/simple-json +//----------------------------------------------------------------------- + +// NOTE: uncomment the following line to make SimpleJson class internal. +//#define SIMPLE_JSON_INTERNAL + +// NOTE: uncomment the following line to make JsonArray and JsonObject class internal. +//#define SIMPLE_JSON_OBJARRAYINTERNAL + +// NOTE: uncomment the following line to enable dynamic support. +//#define SIMPLE_JSON_DYNAMIC + +// NOTE: uncomment the following line to enable DataContract support. +#define SIMPLE_JSON_DATACONTRACT + +// NOTE: uncomment the following line to use Reflection.Emit (better performance) instead of method.invoke(). +// don't enable ReflectionEmit for WinRT, Silverlight and WP7. +//#define SIMPLE_JSON_REFLECTIONEMIT + +// NOTE: uncomment the following line if you are compiling under Window Metro style application/library. +// usually already defined in properties +//#define NETFX_CORE; + +// original json parsing code from http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html + +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +#if SIMPLE_JSON_DYNAMIC +using System.Dynamic; +#endif +using System.Globalization; +using System.Reflection; +#if SIMPLE_JSON_REFLECTIONEMIT +using System.Reflection.Emit; +#endif +#if SIMPLE_JSON_DATACONTRACT +using System.Runtime.Serialization; +#endif +using System.Text; +using PitayaSimpleJson.Reflection; + +namespace PitayaSimpleJson +{ + #region JsonArray + + /// + /// Represents the json array. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] + #if SIMPLE_JSON_OBJARRAYINTERNAL + internal + #else + public + #endif + class JsonArray : List + { + /// + /// Initializes a new instance of the class. + /// + public JsonArray() { } + + /// + /// Initializes a new instance of the class. + /// + /// The capacity of the json array. + public JsonArray(int capacity) : base(capacity) { } + + /// + /// The json representation of the array. + /// + /// The json representation of the array. + public override string ToString() + { + return SimpleJson.SerializeObject(this) ?? string.Empty; + } + } + + #endregion + + #region JsonObject + + /// + /// Represents the json object. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] + #if SIMPLE_JSON_OBJARRAYINTERNAL + internal + #else + public + #endif + class JsonObject : + #if SIMPLE_JSON_DYNAMIC + DynamicObject, + #endif + IDictionary + { + /// + /// The internal member dictionary. + /// + private readonly Dictionary _members = new Dictionary(); + + /// + /// Gets the at the specified index. + /// + /// + public object this[int index] + { + get { return GetAtIndex(_members, index); } + } + + internal static object GetAtIndex(IDictionary obj, int index) + { + if (obj == null) + throw new ArgumentNullException("obj"); + + if (index >= obj.Count) + throw new ArgumentOutOfRangeException("index"); + + int i = 0; + foreach (KeyValuePair o in obj) + if (i++ == index) return o.Value; + + return null; + } + + /// + /// Adds the specified key. + /// + /// The key. + /// The value. + public void Add(string key, object value) + { + _members.Add(key, value); + } + + /// + /// Determines whether the specified key contains key. + /// + /// The key. + /// + /// true if the specified key contains key; otherwise, false. + /// + public bool ContainsKey(string key) + { + return _members.ContainsKey(key); + } + + /// + /// Gets the keys. + /// + /// The keys. + public ICollection Keys + { + get { return _members.Keys; } + } + + /// + /// Removes the specified key. + /// + /// The key. + /// + public bool Remove(string key) + { + return _members.Remove(key); + } + + /// + /// Tries the get value. + /// + /// The key. + /// The value. + /// + public bool TryGetValue(string key, out object value) + { + return _members.TryGetValue(key, out value); + } + + /// + /// Gets the values. + /// + /// The values. + public ICollection Values + { + get { return _members.Values; } + } + + /// + /// Gets or sets the with the specified key. + /// + /// + public object this[string key] + { + get { return _members[key]; } + set { _members[key] = value; } + } + + /// + /// Adds the specified item. + /// + /// The item. + public void Add(KeyValuePair item) + { + _members.Add(item.Key, item.Value); + } + + /// + /// Clears this instance. + /// + public void Clear() + { + _members.Clear(); + } + + /// + /// Determines whether [contains] [the specified item]. + /// + /// The item. + /// + /// true if [contains] [the specified item]; otherwise, false. + /// + public bool Contains(KeyValuePair item) + { + return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value; + } + + /// + /// Copies to. + /// + /// The array. + /// Index of the array. + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + int num = Count; + foreach (KeyValuePair kvp in this) + { + array[arrayIndex++] = kvp; + + if (--num <= 0) + return; + } + } + + /// + /// Gets the count. + /// + /// The count. + public int Count + { + get { return _members.Count; } + } + + /// + /// Gets a value indicating whether this instance is read only. + /// + /// + /// true if this instance is read only; otherwise, false. + /// + public bool IsReadOnly + { + get { return false; } + } + + /// + /// Removes the specified item. + /// + /// The item. + /// + public bool Remove(KeyValuePair item) + { + return _members.Remove(item.Key); + } + + /// + /// Gets the enumerator. + /// + /// + public IEnumerator> GetEnumerator() + { + return _members.GetEnumerator(); + } + + /// + /// Returns an enumerator that iterates through a collection. + /// + /// + /// An object that can be used to iterate through the collection. + /// + IEnumerator IEnumerable.GetEnumerator() + { + return _members.GetEnumerator(); + } + + /// + /// Returns a json that represents the current . + /// + /// + /// A json that represents the current . + /// + public override string ToString() + { + return SimpleJson.SerializeObject(this); + } + + #if SIMPLE_JSON_DYNAMIC + /// + /// Provides implementation for type conversion operations. Classes derived from the class can override this method to specify dynamic behavior for operations that convert an object from one type to another. + /// + /// Provides information about the conversion operation. The binder.Type property provides the type to which the object must be converted. For example, for the statement (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), where sampleObject is an instance of the class derived from the class, binder.Type returns the type. The binder.Explicit property provides information about the kind of conversion that occurs. It returns true for explicit conversion and false for implicit conversion. + /// The result of the type conversion operation. + /// + /// Alwasy returns true. + /// + public override bool TryConvert(ConvertBinder binder, out object result) + { + // + if (binder == (ConvertBinder)null) + throw new ArgumentNullException("binder"); + // + Type targetType = binder.Type; + + if ((targetType == typeof(IEnumerable)) || + (targetType == typeof(IEnumerable>)) || + (targetType == typeof(IDictionary)) || + #if NETFX_CORE + (targetType == typeof(IDictionary<,>)) + #else + (targetType == typeof(IDictionary)) + #endif + ) + { + result = this; + return true; + } + + return base.TryConvert(binder, out result); + } + + /// + /// Provides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic. + /// + /// Provides information about the deletion. + /// + /// Alwasy returns true. + /// + public override bool TryDeleteMember(DeleteMemberBinder binder) + { + // + if (binder == (DeleteMemberBinder)null) + throw new ArgumentNullException("binder"); + // + return _members.Remove(binder.Name); + } + + /// + /// Provides the implementation for operations that get a value by index. Classes derived from the class can override this method to specify dynamic behavior for indexing operations. + /// + /// Provides information about the operation. + /// The indexes that are used in the operation. For example, for the sampleObject[3] operation in C# (sampleObject(3) in Visual Basic), where sampleObject is derived from the DynamicObject class, is equal to 3. + /// The result of the index operation. + /// + /// Alwasy returns true. + /// + public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) + { + if (indexes.Length == 1) + { + result = ((IDictionary)this)[(string)indexes[0]]; + return true; + } + result = (object)null; + return true; + } + + /// + /// Provides the implementation for operations that get member values. Classes derived from the class can override this method to specify dynamic behavior for operations such as getting a value for a property. + /// + /// Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive. + /// The result of the get operation. For example, if the method is called for a property, you can assign the property value to . + /// + /// Alwasy returns true. + /// + public override bool TryGetMember(GetMemberBinder binder, out object result) + { + object value; + if (_members.TryGetValue(binder.Name, out value)) + { + result = value; + return true; + } + result = (object)null; + return true; + } + + /// + /// Provides the implementation for operations that set a value by index. Classes derived from the class can override this method to specify dynamic behavior for operations that access objects by a specified index. + /// + /// Provides information about the operation. + /// The indexes that are used in the operation. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the class, is equal to 3. + /// The value to set to the object that has the specified index. For example, for the sampleObject[3] = 10 operation in C# (sampleObject(3) = 10 in Visual Basic), where sampleObject is derived from the class, is equal to 10. + /// + /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown. + /// + public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) + { + if (indexes.Length == 1) + { + ((IDictionary)this)[(string)indexes[0]] = value; + return true; + } + + return base.TrySetIndex(binder, indexes, value); + } + + /// + /// Provides the implementation for operations that set member values. Classes derived from the class can override this method to specify dynamic behavior for operations such as setting a value for a property. + /// + /// Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive. + /// The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the class, the is "Test". + /// + /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.) + /// + public override bool TrySetMember(SetMemberBinder binder, object value) + { + // + if (binder == (SetMemberBinder)null) + throw new ArgumentNullException("binder"); + // + _members[binder.Name] = value; + return true; + } + + /// + /// Returns the enumeration of all dynamic member names. + /// + /// + /// A sequence that contains dynamic member names. + /// + public override IEnumerable GetDynamicMemberNames() + { + foreach (var key in Keys) + yield return key; + } + #endif + } + + #endregion +} + +namespace PitayaSimpleJson +{ + #region JsonParser + + /// + /// This class encodes and decodes JSON strings. + /// Spec. details, see http://www.json.org/ + /// + /// JSON uses Arrays and Objects. These correspond here to the datatypes JsonArray(IList<object>) and JsonObject(IDictionary<string,object>). + /// All numbers are parsed to doubles. + /// + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class SimpleJson + { + private const int TOKEN_NONE = 0; + private const int TOKEN_CURLY_OPEN = 1; + private const int TOKEN_CURLY_CLOSE = 2; + private const int TOKEN_SQUARED_OPEN = 3; + private const int TOKEN_SQUARED_CLOSE = 4; + private const int TOKEN_COLON = 5; + private const int TOKEN_COMMA = 6; + private const int TOKEN_STRING = 7; + private const int TOKEN_NUMBER = 8; + private const int TOKEN_TRUE = 9; + private const int TOKEN_FALSE = 10; + private const int TOKEN_NULL = 11; + + private const int BUILDER_CAPACITY = 2000; + + /// + /// Parses the string json into a value + /// + /// A JSON string. + /// An IList<object>, a IDictionary<string,object>, a double, a string, null, true, or false + public static object DeserializeObject(string json) + { + object @object; + if (TryDeserializeObject(json, out @object)) + return @object; + throw new System.Runtime.Serialization.SerializationException("Invalid JSON string"); + } + + /// + /// Try parsing the json string into a value. + /// + /// + /// A JSON string. + /// + /// + /// The object. + /// + /// + /// Returns true if successfull otherwise false. + /// + public static bool TryDeserializeObject(string json, out object @object) + { + bool success = true; + if (json != null) + { + char[] charArray = json.ToCharArray(); + int index = 0; + @object = ParseValue(charArray, ref index, ref success); + } + else + @object = null; + + return success; + } + + public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy) + { + return DeserializeObject(json, type, jsonSerializerStrategy, null); + } + + public static object DeserializeObject(string json, Type type, IJsonSerializerStrategy jsonSerializerStrategy, object defaultValue = null) + { + object jsonObject = DeserializeObject(json); + + return type == null || jsonObject != null && + #if NETFX_CORE + jsonObject.GetType().GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()) + #else + jsonObject.GetType().IsAssignableFrom(type) + #endif + ? jsonObject + : (jsonSerializerStrategy ?? CurrentJsonSerializerStrategy).DeserializeObject(jsonObject, type, defaultValue); + } + + public static object DeserializeObject(string json, Type type) + { + return DeserializeObject(json, type, null, null); + } + + public static T DeserializeObject(string json, T defaultValue) + { + return (T)DeserializeObject(json, typeof(T), null, defaultValue); + } + + public static T DeserializeObject(string json, IJsonSerializerStrategy jsonSerializerStrategy) + { + return (T)DeserializeObject(json, typeof(T), jsonSerializerStrategy, null); + } + + public static T DeserializeObject(string json) + { + return (T)DeserializeObject(json, typeof(T), null, null); + } + + /// + /// Converts a IDictionary<string,object> / IList<object> object into a JSON string + /// + /// A IDictionary<string,object> / IList<object> + /// Serializer strategy to use + /// A JSON encoded string, or null if object 'json' is not serializable + public static string SerializeObject(object json, IJsonSerializerStrategy jsonSerializerStrategy) + { + StringBuilder builder = new StringBuilder(BUILDER_CAPACITY); + bool success = SerializeValue(jsonSerializerStrategy, json, builder); + return (success ? builder.ToString() : null); + } + + public static string SerializeObject(object json) + { + return SerializeObject(json, CurrentJsonSerializerStrategy); + } + + public static string EscapeToJavascriptString(string jsonString) + { + if (string.IsNullOrEmpty(jsonString)) + { + return jsonString; + } + + StringBuilder sb = new StringBuilder(); + char c; + + for (int i = 0; i < jsonString.Length; ) + { + c = jsonString[i++]; + + if (c == '\\') + { + int remainingLength = jsonString.Length - i; + if (remainingLength >= 2) + { + char lookahead = jsonString[i]; + if (lookahead == '\\') + { + sb.Append('\\'); + ++i; + } + else if (lookahead == '"') + { + sb.Append("\""); + ++i; + } + else if (lookahead == 't') + { + sb.Append('\t'); + ++i; + } + else if (lookahead == 'b') + { + sb.Append('\b'); + ++i; + } + else if (lookahead == 'n') + { + sb.Append('\n'); + ++i; + } + else if (lookahead == 'r') + { + sb.Append('\r'); + ++i; + } + } + } + else + { + sb.Append(c); + } + } + + return sb.ToString(); + } + + protected static IDictionary ParseObject(char[] json, ref int index, ref bool success) + { + IDictionary table = new JsonObject(); + int token; + + // { + NextToken(json, ref index); + + bool done = false; + while (!done) + { + token = LookAhead(json, index); + if (token == TOKEN_NONE) + { + success = false; + return null; + } + else if (token == TOKEN_COMMA) + NextToken(json, ref index); + else if (token == TOKEN_CURLY_CLOSE) + { + NextToken(json, ref index); + return table; + } + else + { + // name + string name = ParseString(json, ref index, ref success); + if (!success) + { + success = false; + return null; + } + + // : + token = NextToken(json, ref index); + if (token != TOKEN_COLON) + { + success = false; + return null; + } + + // value + object value = ParseValue(json, ref index, ref success); + if (!success) + { + success = false; + return null; + } + + table[name] = value; + } + } + + return table; + } + + protected static JsonArray ParseArray(char[] json, ref int index, ref bool success) + { + JsonArray array = new JsonArray(); + + // [ + NextToken(json, ref index); + + bool done = false; + while (!done) + { + int token = LookAhead(json, index); + if (token == TOKEN_NONE) + { + success = false; + return null; + } + else if (token == TOKEN_COMMA) + NextToken(json, ref index); + else if (token == TOKEN_SQUARED_CLOSE) + { + NextToken(json, ref index); + break; + } + else + { + object value = ParseValue(json, ref index, ref success); + if (!success) + return null; + array.Add(value); + } + } + + return array; + } + + protected static object ParseValue(char[] json, ref int index, ref bool success) + { + switch (LookAhead(json, index)) + { + case TOKEN_STRING: + return ParseString(json, ref index, ref success); + case TOKEN_NUMBER: + return ParseNumber(json, ref index, ref success); + case TOKEN_CURLY_OPEN: + return ParseObject(json, ref index, ref success); + case TOKEN_SQUARED_OPEN: + return ParseArray(json, ref index, ref success); + case TOKEN_TRUE: + NextToken(json, ref index); + return true; + case TOKEN_FALSE: + NextToken(json, ref index); + return false; + case TOKEN_NULL: + NextToken(json, ref index); + return null; + case TOKEN_NONE: + break; + } + + success = false; + return null; + } + + protected static string ParseString(char[] json, ref int index, ref bool success) + { + StringBuilder s = new StringBuilder(BUILDER_CAPACITY); + char c; + + EatWhitespace(json, ref index); + + // " + c = json[index++]; + + bool complete = false; + while (!complete) + { + if (index == json.Length) + { + break; + } + + c = json[index++]; + if (c == '"') + { + complete = true; + break; + } + else if (c == '\\') + { + if (index == json.Length) + break; + c = json[index++]; + if (c == '"') + s.Append('"'); + else if (c == '\\') + s.Append('\\'); + else if (c == '/') + s.Append('/'); + else if (c == 'b') + s.Append('\b'); + else if (c == 'f') + s.Append('\f'); + else if (c == 'n') + s.Append('\n'); + else if (c == 'r') + s.Append('\r'); + else if (c == 't') + s.Append('\t'); + else if (c == 'u') + { + int remainingLength = json.Length - index; + if (remainingLength >= 4) + { + // parse the 32 bit hex into an integer codepoint + uint codePoint; + if ( + !(success = + UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, + CultureInfo.InvariantCulture, out codePoint))) + return ""; + + // convert the integer codepoint to a unicode char and add to string + + if (0xD800 <= codePoint && codePoint <= 0xDBFF) // if high surrogate + { + index += 4; // skip 4 chars + remainingLength = json.Length - index; + if (remainingLength >= 6) + { + uint lowCodePoint; + if (new string(json, index, 2) == "\\u" && + UInt32.TryParse(new string(json, index + 2, 4), NumberStyles.HexNumber, + CultureInfo.InvariantCulture, out lowCodePoint)) + { + if (0xDC00 <= lowCodePoint && lowCodePoint <= 0xDFFF) // if low surrogate + { + s.Append((char)codePoint); + s.Append((char)lowCodePoint); + index += 6; // skip 6 chars + continue; + } + } + } + success = false; // invalid surrogate pair + return ""; + } + #if SILVERLIGHT + s.Append(ConvertFromUtf32((int)codePoint)); + #else + s.Append(Char.ConvertFromUtf32((int)codePoint)); + #endif + // skip 4 chars + index += 4; + } + else + break; + } + } + else + s.Append(c); + } + + if (!complete) + { + success = false; + return null; + } + + return s.ToString(); + } + + #if SILVERLIGHT + private static string ConvertFromUtf32(int utf32) + { + // http://www.java2s.com/Open-Source/CSharp/2.6.4-mono-.net-core/System/System/Char.cs.htm + if (utf32 < 0 || utf32 > 0x10FFFF) + throw new ArgumentOutOfRangeException("utf32", "The argument must be from 0 to 0x10FFFF."); + if (0xD800 <= utf32 && utf32 <= 0xDFFF) + throw new ArgumentOutOfRangeException("utf32", "The argument must not be in surrogate pair range."); + if (utf32 < 0x10000) + return new string((char)utf32, 1); + utf32 -= 0x10000; + return new string(new char[] {(char) ((utf32 >> 10) + 0xD800),(char) (utf32 % 0x0400 + 0xDC00)}); + } + #endif + + protected static object ParseNumber(char[] json, ref int index, ref bool success) + { + EatWhitespace(json, ref index); + + int lastIndex = GetLastIndexOfNumber(json, index); + int charLength = (lastIndex - index) + 1; + + object returnNumber; + string str = new string(json, index, charLength); + if (str.IndexOf(".", StringComparison.OrdinalIgnoreCase) != -1 || str.IndexOf("e", StringComparison.OrdinalIgnoreCase) != -1) + { + double number; + success = double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); + returnNumber = number; + } + else + { + long number; + success = long.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number); + returnNumber = number; + } + + index = lastIndex + 1; + return returnNumber; + } + + protected static int GetLastIndexOfNumber(char[] json, int index) + { + int lastIndex; + + for (lastIndex = index; lastIndex < json.Length; lastIndex++) + if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) break; + return lastIndex - 1; + } + + protected static void EatWhitespace(char[] json, ref int index) + { + for (; index < json.Length; index++) + if (" \t\n\r\b\f".IndexOf(json[index]) == -1) break; + } + + protected static int LookAhead(char[] json, int index) + { + int saveIndex = index; + return NextToken(json, ref saveIndex); + } + + [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] + protected static int NextToken(char[] json, ref int index) + { + EatWhitespace(json, ref index); + + if (index == json.Length) + return TOKEN_NONE; + + char c = json[index]; + index++; + switch (c) + { + case '{': + return TOKEN_CURLY_OPEN; + case '}': + return TOKEN_CURLY_CLOSE; + case '[': + return TOKEN_SQUARED_OPEN; + case ']': + return TOKEN_SQUARED_CLOSE; + case ',': + return TOKEN_COMMA; + case '"': + return TOKEN_STRING; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '-': + return TOKEN_NUMBER; + case ':': + return TOKEN_COLON; + } + index--; + + int remainingLength = json.Length - index; + + // false + if (remainingLength >= 5) + { + if (json[index] == 'f' && + json[index + 1] == 'a' && + json[index + 2] == 'l' && + json[index + 3] == 's' && + json[index + 4] == 'e') + { + index += 5; + return TOKEN_FALSE; + } + } + + // true + if (remainingLength >= 4) + { + if (json[index] == 't' && + json[index + 1] == 'r' && + json[index + 2] == 'u' && + json[index + 3] == 'e') + { + index += 4; + return TOKEN_TRUE; + } + } + + // null + if (remainingLength >= 4) + { + if (json[index] == 'n' && + json[index + 1] == 'u' && + json[index + 2] == 'l' && + json[index + 3] == 'l') + { + index += 4; + return TOKEN_NULL; + } + } + + return TOKEN_NONE; + } + + protected static bool SerializeValue(IJsonSerializerStrategy jsonSerializerStrategy, object value, StringBuilder builder) + { + bool success = true; + + if (value is string) + success = SerializeString((string)value, builder); + else if (value is IDictionary) + { + IDictionary dict = (IDictionary)value; + success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder); + } + else if (value is IDictionary) + { + IDictionary dict = (IDictionary)value; + success = SerializeObject(jsonSerializerStrategy, dict.Keys, dict.Values, builder); + } + else if (value is IEnumerable) + success = SerializeArray(jsonSerializerStrategy, (IEnumerable)value, builder); + else if (IsNumeric(value)) + success = SerializeNumber(value, builder); + else if (value is Boolean) + builder.Append((bool)value ? "true" : "false"); + else if (value == null) + builder.Append("null"); + else + { + object serializedObject; + success = jsonSerializerStrategy.SerializeNonPrimitiveObject(value, out serializedObject); + if (success) + SerializeValue(jsonSerializerStrategy, serializedObject, builder); + } + + return success; + } + + protected static bool SerializeObject(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable keys, IEnumerable values, StringBuilder builder) + { + builder.Append("{"); + + IEnumerator ke = keys.GetEnumerator(); + IEnumerator ve = values.GetEnumerator(); + + bool first = true; + while (ke.MoveNext() && ve.MoveNext()) + { + object key = ke.Current; + object value = ve.Current; + + if (!first) + builder.Append(","); + + if (key is string) + SerializeString((string)key, builder); + else + if (!SerializeValue(jsonSerializerStrategy, value, builder)) return false; + + builder.Append(":"); + if (!SerializeValue(jsonSerializerStrategy, value, builder)) + return false; + + first = false; + } + + builder.Append("}"); + return true; + } + + protected static bool SerializeArray(IJsonSerializerStrategy jsonSerializerStrategy, IEnumerable anArray, StringBuilder builder) + { + builder.Append("["); + + bool first = true; + foreach (object value in anArray) + { + if (!first) + builder.Append(","); + + if (!SerializeValue(jsonSerializerStrategy, value, builder)) + return false; + + first = false; + } + + builder.Append("]"); + return true; + } + + protected static bool SerializeString(string aString, StringBuilder builder) + { + builder.Append("\""); + + char[] charArray = aString.ToCharArray(); + for (int i = 0; i < charArray.Length; i++) + { + char c = charArray[i]; + if (c == '"') + builder.Append("\\\""); + else if (c == '\\') + builder.Append("\\\\"); + else if (c == '\b') + builder.Append("\\b"); + else if (c == '\f') + builder.Append("\\f"); + else if (c == '\n') + builder.Append("\\n"); + else if (c == '\r') + builder.Append("\\r"); + else if (c == '\t') + builder.Append("\\t"); + else + builder.Append(c); + } + + builder.Append("\""); + return true; + } + + protected static bool SerializeNumber(object number, StringBuilder builder) + { + if (number is long) + { + builder.Append(((long)number).ToString(CultureInfo.InvariantCulture)); + } + else if (number is ulong) + { + builder.Append(((ulong)number).ToString(CultureInfo.InvariantCulture)); + } + else if (number is int) + { + builder.Append(((int)number).ToString(CultureInfo.InvariantCulture)); + } + else if (number is uint) + { + builder.Append(((uint)number).ToString(CultureInfo.InvariantCulture)); + } + else if (number is decimal) + { + builder.Append(((decimal)number).ToString(CultureInfo.InvariantCulture)); + } + else if (number is float) + { + builder.Append(((float)number).ToString(CultureInfo.InvariantCulture)); + } + else + { + builder.Append(Convert.ToDouble(number, CultureInfo.InvariantCulture).ToString("r", CultureInfo.InvariantCulture)); + } + + return true; + } + + /// + /// Determines if a given object is numeric in any way + /// (can be integer, double, null, etc). + /// + protected static bool IsNumeric(object value) + { + if (value is sbyte) return true; + if (value is byte) return true; + if (value is short) return true; + if (value is ushort) return true; + if (value is int) return true; + if (value is uint) return true; + if (value is long) return true; + if (value is ulong) return true; + if (value is float) return true; + if (value is double) return true; + if (value is decimal) return true; + return false; + } + + private static IJsonSerializerStrategy currentJsonSerializerStrategy; + public static IJsonSerializerStrategy CurrentJsonSerializerStrategy + { + get + { + // todo: implement locking mechanism. + return currentJsonSerializerStrategy ?? + (currentJsonSerializerStrategy = + #if SIMPLE_JSON_DATACONTRACT + DataContractJsonSerializerStrategy + #else + PocoJsonSerializerStrategy + #endif + ); + } + + set + { + currentJsonSerializerStrategy = value; + } + } + + private static PocoJsonSerializerStrategy pocoJsonSerializerStrategy; + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] + public static PocoJsonSerializerStrategy PocoJsonSerializerStrategy + { + get + { + // todo: implement locking mechanism. + return pocoJsonSerializerStrategy ?? (pocoJsonSerializerStrategy = new PocoJsonSerializerStrategy()); + } + } + + #if SIMPLE_JSON_DATACONTRACT + + private static DataContractJsonSerializerStrategy dataContractJsonSerializerStrategy; + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] + public static DataContractJsonSerializerStrategy DataContractJsonSerializerStrategy + { + get + { + // todo: implement locking mechanism. + return dataContractJsonSerializerStrategy ?? (dataContractJsonSerializerStrategy = new DataContractJsonSerializerStrategy()); + } + } + + #endif + } + + #endregion + + #region Simple Json Serializer Strategies + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + interface IJsonSerializerStrategy + { + bool SerializeNonPrimitiveObject(object input, out object output); + + object DeserializeObject(object value, Type type, object defaultValue = null); + } + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class PocoJsonSerializerStrategy : IJsonSerializerStrategy + { + internal CacheResolver CacheResolver; + + private static readonly string[] Iso8601Format = new string[] + { + @"yyyy-MM-dd\THH:mm:ss.FFFFFFF\Z", + @"yyyy-MM-dd\THH:mm:ss\Z", + @"yyyy-MM-dd\THH:mm:ssK" + }; + + public PocoJsonSerializerStrategy() + { + CacheResolver = new CacheResolver(BuildMap); + } + + protected virtual void BuildMap(Type type, SafeDictionary memberMaps) + { + #if NETFX_CORE + foreach (PropertyInfo info in type.GetTypeInfo().DeclaredProperties) { + var getMethod = info.GetMethod; + if(getMethod==null || !getMethod.IsPublic || getMethod.IsStatic) continue; + #else + foreach (PropertyInfo info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public)) + { + #endif + memberMaps.Add(info.Name, new CacheResolver.MemberMap(info)); + } + #if NETFX_CORE + foreach (FieldInfo info in type.GetTypeInfo().DeclaredFields) { + if(!info.IsPublic || info.IsStatic) continue; + #else + foreach (FieldInfo info in type.GetFields(BindingFlags.Public | BindingFlags.Instance)) + { + #endif + memberMaps.Add(info.Name, new CacheResolver.MemberMap(info)); + } + } + + public virtual bool SerializeNonPrimitiveObject(object input, out object output) + { + return TrySerializeKnownTypes(input, out output) || TrySerializeUnknownTypes(input, out output); + } + + [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] + public virtual object DeserializeObject(object value, Type type, object defaultInstance = null) + { + object obj = null; + if (value is string) + { + string str = value as string; + if(!string.IsNullOrEmpty(str) && (type == typeof(DateTime) || (ReflectionUtils.IsNullableType(type) && Nullable.GetUnderlyingType(type) == typeof(DateTime)) )) + obj = DateTime.ParseExact(str, Iso8601Format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); + else + obj = str; + } + else if (value is bool) + obj = value; + else if (value == null) + obj = null; + else if ((value is long && type == typeof(long)) || (value is double && type == typeof(double))) + obj = value; + else if ((value is double && type != typeof(double)) || (value is long && type != typeof(long))) + { + obj = + #if NETFX_CORE + type == typeof(int) || type == typeof(long) || type == typeof(double) ||type == typeof(float) || type == typeof(bool) || type == typeof(decimal) ||type == typeof(byte) || type == typeof(short) + #else + typeof(IConvertible).IsAssignableFrom(type) + #endif + ? Convert.ChangeType(value, type, CultureInfo.InvariantCulture) : value; + } + else + { + if (value is IDictionary) + { + IDictionary jsonObject = (IDictionary) value; + + if (ReflectionUtils.IsTypeDictionary(type)) + { + // if dictionary then + #if NETFX_CORE + Type keyType = type.GetTypeInfo().GenericTypeArguments[0]; + Type valueType = type.GetTypeInfo().GenericTypeArguments[1]; + #else + Type keyType = type.GetGenericArguments()[0]; + Type valueType = type.GetGenericArguments()[1]; + #endif + + Type genericType = typeof (Dictionary<,>).MakeGenericType(keyType, valueType); + + #if NETFX_CORE + dynamic dict = CacheResolver.GetNewInstance(genericType); + #else + IDictionary dict = (IDictionary) CacheResolver.GetNewInstance(genericType); + #endif + foreach (KeyValuePair kvp in jsonObject) + { + dict.Add(DeserializeObject(kvp.Key, keyType), DeserializeObject(kvp.Value, valueType)); + } + + obj = dict; + } + else + { + if(defaultInstance != null){ + obj = defaultInstance; + }else{ + obj = CacheResolver.GetNewInstance(type); + } + + SafeDictionary maps = CacheResolver.LoadMaps(type); + + if (maps == null) + { + obj = value; + } + else + { + foreach (KeyValuePair keyValuePair in maps) + { + CacheResolver.MemberMap v = keyValuePair.Value; + if (v.Setter == null) + continue; + + string jsonKey = keyValuePair.Key; + if (jsonObject.ContainsKey(jsonKey)) + { + object jsonValue = DeserializeObject(jsonObject[jsonKey], v.Type); + v.Setter(obj, jsonValue); + } + } + } + } + } + else if (value is IList) + { + IList jsonObject = (IList) value; + IList list = null; + + if (type.IsArray) + { + list = (IList) Activator.CreateInstance(type, jsonObject.Count); + int i = 0; + foreach (object o in jsonObject) + list[i++] = DeserializeObject(o, type.GetElementType()); + } + else if (ReflectionUtils.IsTypeGenericeCollectionInterface(type) || + #if NETFX_CORE + typeof(IList).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()) + #else + typeof (IList).IsAssignableFrom(type) + #endif + ) + { + #if NETFX_CORE + Type innerType = type.GetTypeInfo().GenericTypeArguments[0]; + #else + Type innerType = type.GetGenericArguments()[0]; + #endif + Type genericType = typeof (List<>).MakeGenericType(innerType); + list = (IList) CacheResolver.GetNewInstance(genericType); + foreach (object o in jsonObject) + list.Add(DeserializeObject(o, innerType)); + } + + obj = list; + } + + return obj; + } + + if (ReflectionUtils.IsNullableType(type)) + return ReflectionUtils.ToNullableType(obj, type); + + return obj; + } + + protected virtual object SerializeEnum(Enum p) + { + return Convert.ToDouble(p, CultureInfo.InvariantCulture); + } + + protected virtual bool TrySerializeKnownTypes(object input, out object output) + { + bool returnValue = true; + if (input is DateTime) + output = ((DateTime)input).ToUniversalTime().ToString(Iso8601Format[0], CultureInfo.InvariantCulture); + else if (input is Guid) + output = ((Guid)input).ToString("D"); + else if (input is Uri) + output = input.ToString(); + else if (input is Enum) + output = SerializeEnum((Enum)input); + else + { + returnValue = false; + output = null; + } + + return returnValue; + } + + protected virtual bool TrySerializeUnknownTypes(object input, out object output) + { + output = null; + + // todo: implement caching for types + Type type = input.GetType(); + + if (type.FullName == null) + return false; + + IDictionary obj = new JsonObject(); + + SafeDictionary maps = CacheResolver.LoadMaps(type); + + foreach (KeyValuePair keyValuePair in maps) + { + if (keyValuePair.Value.Getter != null) + obj.Add(keyValuePair.Key, keyValuePair.Value.Getter(input)); + } + + output = obj; + return true; + } + } + + #if SIMPLE_JSON_DATACONTRACT + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class DataContractJsonSerializerStrategy : PocoJsonSerializerStrategy + { + public DataContractJsonSerializerStrategy() + { + CacheResolver = new CacheResolver(BuildMap); + } + + protected override void BuildMap(Type type, SafeDictionary map) + { + bool hasDataContract = ReflectionUtils.GetAttribute(type, typeof(DataContractAttribute)) != null; + if (!hasDataContract) + { + base.BuildMap(type, map); + return; + } + + string jsonKey; + #if NETFX_CORE + foreach (PropertyInfo info in type.GetTypeInfo().DeclaredProperties) + #else + foreach (PropertyInfo info in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) + #endif + { + if (CanAdd(info, out jsonKey)) + map.Add(jsonKey, new CacheResolver.MemberMap(info)); + } + + #if NETFX_CORE + foreach (FieldInfo info in type.GetTypeInfo().DeclaredFields) + #else + foreach (FieldInfo info in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) + #endif + { + if (CanAdd(info, out jsonKey)) + map.Add(jsonKey, new CacheResolver.MemberMap(info)); + } + + // todo implement sorting for DATACONTRACT. + } + + private static bool CanAdd(MemberInfo info, out string jsonKey) + { + jsonKey = null; + + if (ReflectionUtils.GetAttribute(info, typeof(IgnoreDataMemberAttribute)) != null) + return false; + + DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)ReflectionUtils.GetAttribute(info, typeof(DataMemberAttribute)); + + if (dataMemberAttribute == null) + return false; + + jsonKey = string.IsNullOrEmpty(dataMemberAttribute.Name) ? info.Name : dataMemberAttribute.Name; + return true; + } + } + #endif + + #endregion + + #region Reflection helpers + + namespace Reflection + { + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class ReflectionUtils + { + public static Attribute GetAttribute(MemberInfo info, Type type) + { + #if NETFX_CORE + if (info == null || type == null || !info.IsDefined(type)) + return null; + return info.GetCustomAttribute(type); + #else + if (info == null || type == null || !Attribute.IsDefined(info, type)) + return null; + return Attribute.GetCustomAttribute(info, type); + #endif + } + + public static Attribute GetAttribute(Type objectType, Type attributeType) + { + + #if NETFX_CORE + if (objectType == null || attributeType == null || !objectType.GetTypeInfo().IsDefined(attributeType)) + return null; + return objectType.GetTypeInfo().GetCustomAttribute(attributeType); + #else + if (objectType == null || attributeType == null || !Attribute.IsDefined(objectType, attributeType)) + return null; + return Attribute.GetCustomAttribute(objectType, attributeType); + #endif + } + + public static bool IsTypeGenericeCollectionInterface(Type type) + { + #if NETFX_CORE + if (!type.GetTypeInfo().IsGenericType) + #else + if (!type.IsGenericType) + #endif + return false; + + Type genericDefinition = type.GetGenericTypeDefinition(); + + return (genericDefinition == typeof(IList<>) || genericDefinition == typeof(ICollection<>) || genericDefinition == typeof(IEnumerable<>)); + } + + public static bool IsTypeDictionary(Type type) + { + #if NETFX_CORE + if (typeof(IDictionary<,>).GetTypeInfo().IsAssignableFrom(type.GetTypeInfo())) + return true; + + if (!type.GetTypeInfo().IsGenericType) + return false; + #else + if (typeof(IDictionary).IsAssignableFrom(type)) + return true; + + if (!type.IsGenericType) + return false; + #endif + Type genericDefinition = type.GetGenericTypeDefinition(); + return genericDefinition == typeof(IDictionary<,>); + } + + public static bool IsNullableType(Type type) + { + return + #if NETFX_CORE + type.GetTypeInfo().IsGenericType + #else + type.IsGenericType + #endif + && type.GetGenericTypeDefinition() == typeof(Nullable<>); + } + + public static object ToNullableType(object obj, Type nullableType) + { + return obj == null ? null : Convert.ChangeType(obj, Nullable.GetUnderlyingType(nullableType), CultureInfo.InvariantCulture); + } + } + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + delegate object GetHandler(object source); + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + delegate void SetHandler(object source, object value); + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + delegate void MemberMapLoader(Type type, SafeDictionary memberMaps); + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class CacheResolver + { + private readonly MemberMapLoader _memberMapLoader; + private readonly SafeDictionary> _memberMapsCache = new SafeDictionary>(); + + delegate object CtorDelegate(); + readonly static SafeDictionary ConstructorCache = new SafeDictionary(); + + public CacheResolver(MemberMapLoader memberMapLoader) + { + _memberMapLoader = memberMapLoader; + } + + [SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")] + public static object GetNewInstance(Type type) + { + CtorDelegate c; + if (ConstructorCache.TryGetValue(type, out c)) + return c(); + #if SIMPLE_JSON_REFLECTIONEMIT + DynamicMethod dynamicMethod = new DynamicMethod("Create" + type.FullName, typeof(object), Type.EmptyTypes, type, true); + dynamicMethod.InitLocals = true; + ILGenerator generator = dynamicMethod.GetILGenerator(); + if (type.IsValueType) + { + generator.DeclareLocal(type); + generator.Emit(OpCodes.Ldloc_0); + generator.Emit(OpCodes.Box, type); + } + else + { + ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); + if (constructorInfo == null) + throw new Exception(string.Format(CultureInfo.InvariantCulture, "Could not get constructor for {0}.", type)); + generator.Emit(OpCodes.Newobj, constructorInfo); + } + generator.Emit(OpCodes.Ret); + c = (CtorDelegate)dynamicMethod.CreateDelegate(typeof(CtorDelegate)); + ConstructorCache.Add(type, c); + return c(); + #else + #if NETFX_CORE + IEnumerable constructorInfos = type.GetTypeInfo().DeclaredConstructors; + ConstructorInfo constructorInfo = null; + foreach (ConstructorInfo item in constructorInfos) // FirstOrDefault() + { + if (item.GetParameters().Length == 0) // Default ctor - make sure it doesn't contain any parameters + { + constructorInfo = item; + break; + } + } + #else + ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); + #endif + c = delegate { return constructorInfo.Invoke(null); }; + ConstructorCache.Add(type, c); + return c(); + #endif + } + + public SafeDictionary LoadMaps(Type type) + { + if (type == null || type == typeof(object)) + return null; + SafeDictionary maps; + if (_memberMapsCache.TryGetValue(type, out maps)) + return maps; + maps = new SafeDictionary(); + _memberMapLoader(type, maps); + _memberMapsCache.Add(type, maps); + return maps; + } + + #if SIMPLE_JSON_REFLECTIONEMIT + static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) + { + DynamicMethod dynamicMethod = !owner.IsInterface + ? new DynamicMethod(name, returnType, parameterTypes, owner, true) + : new DynamicMethod(name, returnType, parameterTypes, (Module)null, true); + + return dynamicMethod; + } + #endif + + static GetHandler CreateGetHandler(FieldInfo fieldInfo) + { + #if SIMPLE_JSON_REFLECTIONEMIT + Type type = fieldInfo.FieldType; + DynamicMethod dynamicGet = CreateDynamicMethod("Get" + fieldInfo.Name, fieldInfo.DeclaringType, new Type[] { typeof(object) }, fieldInfo.DeclaringType); + ILGenerator getGenerator = dynamicGet.GetILGenerator(); + + getGenerator.Emit(OpCodes.Ldarg_0); + getGenerator.Emit(OpCodes.Ldfld, fieldInfo); + if (type.IsValueType) + getGenerator.Emit(OpCodes.Box, type); + getGenerator.Emit(OpCodes.Ret); + + return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler)); + #else + return delegate(object instance) { return fieldInfo.GetValue(instance); }; + #endif + } + + static SetHandler CreateSetHandler(FieldInfo fieldInfo) + { + if (fieldInfo.IsInitOnly || fieldInfo.IsLiteral) + return null; + #if SIMPLE_JSON_REFLECTIONEMIT + Type type = fieldInfo.FieldType; + DynamicMethod dynamicSet = CreateDynamicMethod("Set" + fieldInfo.Name, null, new Type[] { typeof(object), typeof(object) }, fieldInfo.DeclaringType); + ILGenerator setGenerator = dynamicSet.GetILGenerator(); + + setGenerator.Emit(OpCodes.Ldarg_0); + setGenerator.Emit(OpCodes.Ldarg_1); + if (type.IsValueType) + setGenerator.Emit(OpCodes.Unbox_Any, type); + setGenerator.Emit(OpCodes.Stfld, fieldInfo); + setGenerator.Emit(OpCodes.Ret); + + return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler)); + #else + return delegate(object instance, object value) { fieldInfo.SetValue(instance, value); }; + #endif + } + + static GetHandler CreateGetHandler(PropertyInfo propertyInfo) + { + #if NETFX_CORE + MethodInfo getMethodInfo = propertyInfo.GetMethod; + #else + MethodInfo getMethodInfo = propertyInfo.GetGetMethod(true); + #endif + if (getMethodInfo == null) + return null; + #if SIMPLE_JSON_REFLECTIONEMIT + Type type = propertyInfo.PropertyType; + DynamicMethod dynamicGet = CreateDynamicMethod("Get" + propertyInfo.Name, propertyInfo.DeclaringType, new Type[] { typeof(object) }, propertyInfo.DeclaringType); + ILGenerator getGenerator = dynamicGet.GetILGenerator(); + + getGenerator.Emit(OpCodes.Ldarg_0); + getGenerator.Emit(OpCodes.Call, getMethodInfo); + if (type.IsValueType) + getGenerator.Emit(OpCodes.Box, type); + getGenerator.Emit(OpCodes.Ret); + + return (GetHandler)dynamicGet.CreateDelegate(typeof(GetHandler)); + #else + #if NETFX_CORE + return delegate(object instance) { return getMethodInfo.Invoke(instance, new Type[] { }); }; + #else + return delegate(object instance) { return getMethodInfo.Invoke(instance, Type.EmptyTypes); }; + #endif + #endif + } + + static SetHandler CreateSetHandler(PropertyInfo propertyInfo) + { + #if NETFX_CORE + MethodInfo setMethodInfo = propertyInfo.SetMethod; + #else + MethodInfo setMethodInfo = propertyInfo.GetSetMethod(true); + #endif + if (setMethodInfo == null) + return null; + #if SIMPLE_JSON_REFLECTIONEMIT + Type type = propertyInfo.PropertyType; + DynamicMethod dynamicSet = CreateDynamicMethod("Set" + propertyInfo.Name, null, new Type[] { typeof(object), typeof(object) }, propertyInfo.DeclaringType); + ILGenerator setGenerator = dynamicSet.GetILGenerator(); + + setGenerator.Emit(OpCodes.Ldarg_0); + setGenerator.Emit(OpCodes.Ldarg_1); + if (type.IsValueType) + setGenerator.Emit(OpCodes.Unbox_Any, type); + setGenerator.Emit(OpCodes.Call, setMethodInfo); + setGenerator.Emit(OpCodes.Ret); + return (SetHandler)dynamicSet.CreateDelegate(typeof(SetHandler)); + #else + return delegate(object instance, object value) { setMethodInfo.Invoke(instance, new[] { value }); }; + #endif + } + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + sealed class MemberMap + { + public readonly MemberInfo MemberInfo; + public readonly Type Type; + public readonly GetHandler Getter; + public readonly SetHandler Setter; + + public MemberMap(PropertyInfo propertyInfo) + { + MemberInfo = propertyInfo; + Type = propertyInfo.PropertyType; + Getter = CreateGetHandler(propertyInfo); + Setter = CreateSetHandler(propertyInfo); + } + + public MemberMap(FieldInfo fieldInfo) + { + MemberInfo = fieldInfo; + Type = fieldInfo.FieldType; + Getter = CreateGetHandler(fieldInfo); + Setter = CreateSetHandler(fieldInfo); + } + } + } + + #if SIMPLE_JSON_INTERNAL + internal + #else + public + #endif + class SafeDictionary + { + private readonly object _padlock = new object(); + private readonly Dictionary _dictionary = new Dictionary(); + + public bool TryGetValue(TKey key, out TValue value) + { + return _dictionary.TryGetValue(key, out value); + } + + public TValue this[TKey key] + { + get { return _dictionary[key]; } + } + + public IEnumerator> GetEnumerator() + { + return ((ICollection>)_dictionary).GetEnumerator(); + } + + public void Add(TKey key, TValue value) + { + lock (_padlock) + { + if (_dictionary.ContainsKey(key) == false) + _dictionary.Add(key, value); + } + } + } + } + + #endregion + } diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/PitayaSimpleJson.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/PitayaSimpleJson.cs.meta new file mode 100644 index 00000000..35a9aac4 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/PitayaSimpleJson.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ac918a073c087bc4bb8a4f57aae0472e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/Utils.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/Utils.cs new file mode 100644 index 00000000..1cff1d55 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/Utils.cs @@ -0,0 +1,56 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using Google.Protobuf; +using NPitaya.Models; + +namespace NPitaya.Utils { + + public static class Utils { + + public static string DefaultRemoteNameFunc(string methodName) + { + var name = methodName; + if (name != string.Empty && char.IsUpper(name[0])) + { + name = char.ToLower(name[0]) + name.Substring(1); + } + return name; + } + + public static IEnumerable GetTypesWithAttribute(Assembly assembly, Type attribute) + { + foreach (Type type in assembly.GetTypes()) + { + if (type.GetCustomAttributes(attribute, true).Length > 0) + { + yield return type; + } + } + } + + internal static Protos.Response GetErrorResponse(string code, string msg) + { + var response = new Protos.Response {Error = new Protos.Error {Code = code, Msg = msg}}; + return response; + } + + internal static IntPtr ByteArrayToIntPtr(byte[] data) + { + IntPtr ptr = Marshal.AllocHGlobal(data.Length); + Marshal.Copy(data, 0, ptr, data.Length); + return ptr; + } + + internal static T GetProtoMessageFromResponse(NPitaya.Protos.Response response) + { + var res = (IMessage) Activator.CreateInstance(typeof(T)); + res.MergeFrom(response.Data); + Logger.Debug("getProtoMsgFromResponse: got this res {0}", res); + return (T) res; + } + } + +} diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/Utils.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/Utils.cs.meta new file mode 100644 index 00000000..0286401d --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/Utils/Utils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b427d5b0c67804d49979d37d134eecb0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen.meta new file mode 100644 index 00000000..1cee0d2b --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 69dd8a24090ab944398f64b8c2930305 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Bind.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Bind.cs new file mode 100644 index 00000000..d7a1132d --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Bind.cs @@ -0,0 +1,252 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: bind.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from bind.proto + public static partial class BindReflection { + + #region Descriptor + /// File descriptor for bind.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static BindReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CgpiaW5kLnByb3RvEgZwcm90b3MiIwoHQmluZE1zZxILCgN1aWQYASABKAkS", + "CwoDZmlkGAIgASgJQjxaKWdpdGh1Yi5jb20vdG9wZnJlZWdhbWVzL3BpdGF5", + "YS9wa2cvcHJvdG9zqgIOTlBpdGF5YS5Qcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.BindMsg), global::NPitaya.Protos.BindMsg.Parser, new[]{ "Uid", "Fid" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class BindMsg : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new BindMsg()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.BindReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public BindMsg() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public BindMsg(BindMsg other) : this() { + uid_ = other.uid_; + fid_ = other.fid_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public BindMsg Clone() { + return new BindMsg(this); + } + + /// Field number for the "uid" field. + public const int UidFieldNumber = 1; + private string uid_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Uid { + get { return uid_; } + set { + uid_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "fid" field. + public const int FidFieldNumber = 2; + private string fid_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Fid { + get { return fid_; } + set { + fid_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as BindMsg); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(BindMsg other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Uid != other.Uid) return false; + if (Fid != other.Fid) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Uid.Length != 0) hash ^= Uid.GetHashCode(); + if (Fid.Length != 0) hash ^= Fid.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Uid.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Uid); + } + if (Fid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Fid); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Uid.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Uid); + } + if (Fid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Fid); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Uid.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Uid); + } + if (Fid.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Fid); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(BindMsg other) { + if (other == null) { + return; + } + if (other.Uid.Length != 0) { + Uid = other.Uid; + } + if (other.Fid.Length != 0) { + Fid = other.Fid; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Uid = input.ReadString(); + break; + } + case 18: { + Fid = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Uid = input.ReadString(); + break; + } + case 18: { + Fid = input.ReadString(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Bind.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Bind.cs.meta new file mode 100644 index 00000000..9b105786 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Bind.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 45424f7bcef97324ab688ffe884ee3a3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Doc.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Doc.cs new file mode 100644 index 00000000..0a64fce8 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Doc.cs @@ -0,0 +1,216 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: doc.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from doc.proto + public static partial class DocReflection { + + #region Descriptor + /// File descriptor for doc.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static DocReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cglkb2MucHJvdG8SBnByb3RvcyISCgNEb2MSCwoDZG9jGAEgASgJQjxaKWdp", + "dGh1Yi5jb20vdG9wZnJlZWdhbWVzL3BpdGF5YS9wa2cvcHJvdG9zqgIOTlBp", + "dGF5YS5Qcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Doc), global::NPitaya.Protos.Doc.Parser, new[]{ "Doc_" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Doc : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Doc()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.DocReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Doc() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Doc(Doc other) : this() { + doc_ = other.doc_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Doc Clone() { + return new Doc(this); + } + + /// Field number for the "doc" field. + public const int Doc_FieldNumber = 1; + private string doc_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Doc_ { + get { return doc_; } + set { + doc_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Doc); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Doc other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Doc_ != other.Doc_) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Doc_.Length != 0) hash ^= Doc_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Doc_.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Doc_); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Doc_.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Doc_); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Doc_.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Doc_); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Doc other) { + if (other == null) { + return; + } + if (other.Doc_.Length != 0) { + Doc_ = other.Doc_; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Doc_ = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Doc_ = input.ReadString(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Doc.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Doc.cs.meta new file mode 100644 index 00000000..1a7f902f --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Doc.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6c8b3cbdbf4df2249a0054344c56a410 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Docmsg.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Docmsg.cs new file mode 100644 index 00000000..c57aabc3 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Docmsg.cs @@ -0,0 +1,216 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: docmsg.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from docmsg.proto + public static partial class DocmsgReflection { + + #region Descriptor + /// File descriptor for docmsg.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static DocmsgReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cgxkb2Ntc2cucHJvdG8SBnByb3RvcyIbCgZEb2NNc2cSEQoJZ2V0UHJvdG9z", + "GAEgASgIQjxaKWdpdGh1Yi5jb20vdG9wZnJlZWdhbWVzL3BpdGF5YS9wa2cv", + "cHJvdG9zqgIOTlBpdGF5YS5Qcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.DocMsg), global::NPitaya.Protos.DocMsg.Parser, new[]{ "GetProtos" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class DocMsg : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DocMsg()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.DocmsgReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public DocMsg() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public DocMsg(DocMsg other) : this() { + getProtos_ = other.getProtos_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public DocMsg Clone() { + return new DocMsg(this); + } + + /// Field number for the "getProtos" field. + public const int GetProtosFieldNumber = 1; + private bool getProtos_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool GetProtos { + get { return getProtos_; } + set { + getProtos_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as DocMsg); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(DocMsg other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (GetProtos != other.GetProtos) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (GetProtos != false) hash ^= GetProtos.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (GetProtos != false) { + output.WriteRawTag(8); + output.WriteBool(GetProtos); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (GetProtos != false) { + output.WriteRawTag(8); + output.WriteBool(GetProtos); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (GetProtos != false) { + size += 1 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(DocMsg other) { + if (other == null) { + return; + } + if (other.GetProtos != false) { + GetProtos = other.GetProtos; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + GetProtos = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + GetProtos = input.ReadBool(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Docmsg.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Docmsg.cs.meta new file mode 100644 index 00000000..4498fb93 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Docmsg.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 161a888e4794b6a4d9d78a291507df51 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Error.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Error.cs new file mode 100644 index 00000000..959033e1 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Error.cs @@ -0,0 +1,279 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: error.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from error.proto + public static partial class ErrorReflection { + + #region Descriptor + /// File descriptor for error.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static ErrorReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CgtlcnJvci5wcm90bxIGcHJvdG9zIoIBCgVFcnJvchIMCgRjb2RlGAEgASgJ", + "EgsKA21zZxgCIAEoCRItCghtZXRhZGF0YRgDIAMoCzIbLnByb3Rvcy5FcnJv", + "ci5NZXRhZGF0YUVudHJ5Gi8KDU1ldGFkYXRhRW50cnkSCwoDa2V5GAEgASgJ", + "Eg0KBXZhbHVlGAIgASgJOgI4AUI8WilnaXRodWIuY29tL3RvcGZyZWVnYW1l", + "cy9waXRheWEvcGtnL3Byb3Rvc6oCDk5QaXRheWEuUHJvdG9zYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Error), global::NPitaya.Protos.Error.Parser, new[]{ "Code", "Msg", "Metadata" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, }) + })); + } + #endregion + + } + #region Messages + public sealed partial class Error : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Error()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ErrorReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Error() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Error(Error other) : this() { + code_ = other.code_; + msg_ = other.msg_; + metadata_ = other.metadata_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Error Clone() { + return new Error(this); + } + + /// Field number for the "code" field. + public const int CodeFieldNumber = 1; + private string code_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Code { + get { return code_; } + set { + code_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "msg" field. + public const int MsgFieldNumber = 2; + private string msg_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Msg { + get { return msg_; } + set { + msg_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "metadata" field. + public const int MetadataFieldNumber = 3; + private static readonly pbc::MapField.Codec _map_metadata_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 26); + private readonly pbc::MapField metadata_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::MapField Metadata { + get { return metadata_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Error); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Error other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Code != other.Code) return false; + if (Msg != other.Msg) return false; + if (!Metadata.Equals(other.Metadata)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Code.Length != 0) hash ^= Code.GetHashCode(); + if (Msg.Length != 0) hash ^= Msg.GetHashCode(); + hash ^= Metadata.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Code.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Code); + } + if (Msg.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Msg); + } + metadata_.WriteTo(output, _map_metadata_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Code.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Code); + } + if (Msg.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Msg); + } + metadata_.WriteTo(ref output, _map_metadata_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Code.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Code); + } + if (Msg.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Msg); + } + size += metadata_.CalculateSize(_map_metadata_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Error other) { + if (other == null) { + return; + } + if (other.Code.Length != 0) { + Code = other.Code; + } + if (other.Msg.Length != 0) { + Msg = other.Msg; + } + metadata_.Add(other.metadata_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Code = input.ReadString(); + break; + } + case 18: { + Msg = input.ReadString(); + break; + } + case 26: { + metadata_.AddEntriesFrom(input, _map_metadata_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Code = input.ReadString(); + break; + } + case 18: { + Msg = input.ReadString(); + break; + } + case 26: { + metadata_.AddEntriesFrom(ref input, _map_metadata_codec); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Error.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Error.cs.meta new file mode 100644 index 00000000..ab889bb7 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Error.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 451f94b099ac8de4eadacfcf6fcd893b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Kick.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Kick.cs new file mode 100644 index 00000000..c751f598 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Kick.cs @@ -0,0 +1,390 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: kick.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from kick.proto + public static partial class KickReflection { + + #region Descriptor + /// File descriptor for kick.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static KickReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CgpraWNrLnByb3RvEgZwcm90b3MiGQoHS2lja01zZxIOCgZ1c2VySWQYASAB", + "KAkiHAoKS2lja0Fuc3dlchIOCgZraWNrZWQYASABKAhCPFopZ2l0aHViLmNv", + "bS90b3BmcmVlZ2FtZXMvcGl0YXlhL3BrZy9wcm90b3OqAg5OUGl0YXlhLlBy", + "b3Rvc2IGcHJvdG8z")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.KickMsg), global::NPitaya.Protos.KickMsg.Parser, new[]{ "UserId" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.KickAnswer), global::NPitaya.Protos.KickAnswer.Parser, new[]{ "Kicked" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class KickMsg : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new KickMsg()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.KickReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickMsg() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickMsg(KickMsg other) : this() { + userId_ = other.userId_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickMsg Clone() { + return new KickMsg(this); + } + + /// Field number for the "userId" field. + public const int UserIdFieldNumber = 1; + private string userId_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string UserId { + get { return userId_; } + set { + userId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as KickMsg); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(KickMsg other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (UserId != other.UserId) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (UserId.Length != 0) hash ^= UserId.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (UserId.Length != 0) { + output.WriteRawTag(10); + output.WriteString(UserId); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (UserId.Length != 0) { + output.WriteRawTag(10); + output.WriteString(UserId); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (UserId.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(UserId); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(KickMsg other) { + if (other == null) { + return; + } + if (other.UserId.Length != 0) { + UserId = other.UserId; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + UserId = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + UserId = input.ReadString(); + break; + } + } + } + } + #endif + + } + + public sealed partial class KickAnswer : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new KickAnswer()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.KickReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickAnswer() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickAnswer(KickAnswer other) : this() { + kicked_ = other.kicked_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickAnswer Clone() { + return new KickAnswer(this); + } + + /// Field number for the "kicked" field. + public const int KickedFieldNumber = 1; + private bool kicked_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Kicked { + get { return kicked_; } + set { + kicked_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as KickAnswer); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(KickAnswer other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Kicked != other.Kicked) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Kicked != false) hash ^= Kicked.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Kicked != false) { + output.WriteRawTag(8); + output.WriteBool(Kicked); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Kicked != false) { + output.WriteRawTag(8); + output.WriteBool(Kicked); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Kicked != false) { + size += 1 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(KickAnswer other) { + if (other == null) { + return; + } + if (other.Kicked != false) { + Kicked = other.Kicked; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Kicked = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Kicked = input.ReadBool(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Kick.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Kick.cs.meta new file mode 100644 index 00000000..8bfc6a6d --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Kick.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2f4802e2742c33445aac7a2c1dfdd62c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Msg.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Msg.cs new file mode 100644 index 00000000..de8a0ef7 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Msg.cs @@ -0,0 +1,373 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: msg.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from msg.proto + public static partial class MsgReflection { + + #region Descriptor + /// File descriptor for msg.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static MsgReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cgltc2cucHJvdG8SBnByb3RvcyJcCgNNc2cSCgoCaWQYASABKAQSDQoFcm91", + "dGUYAiABKAkSDAoEZGF0YRgDIAEoDBINCgVyZXBseRgEIAEoCRIdCgR0eXBl", + "GAUgASgOMg8ucHJvdG9zLk1zZ1R5cGUqRgoHTXNnVHlwZRIOCgpNc2dSZXF1", + "ZXN0EAASDQoJTXNnTm90aWZ5EAESDwoLTXNnUmVzcG9uc2UQAhILCgdNc2dQ", + "dXNoEANCPFopZ2l0aHViLmNvbS90b3BmcmVlZ2FtZXMvcGl0YXlhL3BrZy9w", + "cm90b3OqAg5OUGl0YXlhLlByb3Rvc2IGcHJvdG8z")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::NPitaya.Protos.MsgType), }, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Msg), global::NPitaya.Protos.Msg.Parser, new[]{ "Id", "Route", "Data", "Reply", "Type" }, null, null, null, null) + })); + } + #endregion + + } + #region Enums + public enum MsgType { + [pbr::OriginalName("MsgRequest")] MsgRequest = 0, + [pbr::OriginalName("MsgNotify")] MsgNotify = 1, + [pbr::OriginalName("MsgResponse")] MsgResponse = 2, + [pbr::OriginalName("MsgPush")] MsgPush = 3, + } + + #endregion + + #region Messages + public sealed partial class Msg : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Msg()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.MsgReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Msg() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Msg(Msg other) : this() { + id_ = other.id_; + route_ = other.route_; + data_ = other.data_; + reply_ = other.reply_; + type_ = other.type_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Msg Clone() { + return new Msg(this); + } + + /// Field number for the "id" field. + public const int IdFieldNumber = 1; + private ulong id_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ulong Id { + get { return id_; } + set { + id_ = value; + } + } + + /// Field number for the "route" field. + public const int RouteFieldNumber = 2; + private string route_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Route { + get { return route_; } + set { + route_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 3; + private pb::ByteString data_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Data { + get { return data_; } + set { + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "reply" field. + public const int ReplyFieldNumber = 4; + private string reply_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Reply { + get { return reply_; } + set { + reply_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "type" field. + public const int TypeFieldNumber = 5; + private global::NPitaya.Protos.MsgType type_ = global::NPitaya.Protos.MsgType.MsgRequest; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.MsgType Type { + get { return type_; } + set { + type_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Msg); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Msg other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Id != other.Id) return false; + if (Route != other.Route) return false; + if (Data != other.Data) return false; + if (Reply != other.Reply) return false; + if (Type != other.Type) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Id != 0UL) hash ^= Id.GetHashCode(); + if (Route.Length != 0) hash ^= Route.GetHashCode(); + if (Data.Length != 0) hash ^= Data.GetHashCode(); + if (Reply.Length != 0) hash ^= Reply.GetHashCode(); + if (Type != global::NPitaya.Protos.MsgType.MsgRequest) hash ^= Type.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Id != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(Id); + } + if (Route.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Route); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (Reply.Length != 0) { + output.WriteRawTag(34); + output.WriteString(Reply); + } + if (Type != global::NPitaya.Protos.MsgType.MsgRequest) { + output.WriteRawTag(40); + output.WriteEnum((int) Type); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Id != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(Id); + } + if (Route.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Route); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (Reply.Length != 0) { + output.WriteRawTag(34); + output.WriteString(Reply); + } + if (Type != global::NPitaya.Protos.MsgType.MsgRequest) { + output.WriteRawTag(40); + output.WriteEnum((int) Type); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Id != 0UL) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Id); + } + if (Route.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Route); + } + if (Data.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); + } + if (Reply.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Reply); + } + if (Type != global::NPitaya.Protos.MsgType.MsgRequest) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Msg other) { + if (other == null) { + return; + } + if (other.Id != 0UL) { + Id = other.Id; + } + if (other.Route.Length != 0) { + Route = other.Route; + } + if (other.Data.Length != 0) { + Data = other.Data; + } + if (other.Reply.Length != 0) { + Reply = other.Reply; + } + if (other.Type != global::NPitaya.Protos.MsgType.MsgRequest) { + Type = other.Type; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Id = input.ReadUInt64(); + break; + } + case 18: { + Route = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + case 34: { + Reply = input.ReadString(); + break; + } + case 40: { + Type = (global::NPitaya.Protos.MsgType) input.ReadEnum(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Id = input.ReadUInt64(); + break; + } + case 18: { + Route = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + case 34: { + Reply = input.ReadString(); + break; + } + case 40: { + Type = (global::NPitaya.Protos.MsgType) input.ReadEnum(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Msg.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Msg.cs.meta new file mode 100644 index 00000000..dba98375 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Msg.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 78b375892e2ffec4d8b3d74384ee320a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Pitaya.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Pitaya.cs new file mode 100644 index 00000000..43a64c75 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Pitaya.cs @@ -0,0 +1,45 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: pitaya.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from pitaya.proto + public static partial class PitayaReflection { + + #region Descriptor + /// File descriptor for pitaya.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static PitayaReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CgxwaXRheWEucHJvdG8SBnByb3RvcxoNcmVxdWVzdC5wcm90bxoOcmVzcG9u", + "c2UucHJvdG8aCnB1c2gucHJvdG8aCmJpbmQucHJvdG8aCmtpY2sucHJvdG8y", + "0gEKBlBpdGF5YRIrCgRDYWxsEg8ucHJvdG9zLlJlcXVlc3QaEC5wcm90b3Mu", + "UmVzcG9uc2UiABIuCgpQdXNoVG9Vc2VyEgwucHJvdG9zLlB1c2gaEC5wcm90", + "b3MuUmVzcG9uc2UiABI4ChFTZXNzaW9uQmluZFJlbW90ZRIPLnByb3Rvcy5C", + "aW5kTXNnGhAucHJvdG9zLlJlc3BvbnNlIgASMQoIS2lja1VzZXISDy5wcm90", + "b3MuS2lja01zZxoSLnByb3Rvcy5LaWNrQW5zd2VyIgBCPFopZ2l0aHViLmNv", + "bS90b3BmcmVlZ2FtZXMvcGl0YXlhL3BrZy9wcm90b3OqAg5OUGl0YXlhLlBy", + "b3Rvc2IGcHJvdG8z")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::NPitaya.Protos.RequestReflection.Descriptor, global::NPitaya.Protos.ResponseReflection.Descriptor, global::NPitaya.Protos.PushReflection.Descriptor, global::NPitaya.Protos.BindReflection.Descriptor, global::NPitaya.Protos.KickReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(null, null, null)); + } + #endregion + + } +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Pitaya.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Pitaya.cs.meta new file mode 100644 index 00000000..43a67ed8 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Pitaya.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 27ebdb22f30bb5d4f97b84f717393cc2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/PitayaGrpc.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/PitayaGrpc.cs new file mode 100644 index 00000000..adc61b18 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/PitayaGrpc.cs @@ -0,0 +1,231 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: pitaya.proto +// +#pragma warning disable 0414, 1591 +#region Designer generated code + +using grpc = global::Grpc.Core; + +namespace NPitaya.Protos { + public static partial class Pitaya + { + static readonly string __ServiceName = "protos.Pitaya"; + + static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context) + { + #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION + if (message is global::Google.Protobuf.IBufferMessage) + { + context.SetPayloadLength(message.CalculateSize()); + global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter()); + context.Complete(); + return; + } + #endif + context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message)); + } + + static class __Helper_MessageCache + { + public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T)); + } + + static T __Helper_DeserializeMessage(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser parser) where T : global::Google.Protobuf.IMessage + { + #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION + if (__Helper_MessageCache.IsBufferMessage) + { + return parser.ParseFrom(context.PayloadAsReadOnlySequence()); + } + #endif + return parser.ParseFrom(context.PayloadAsNewBuffer()); + } + + static readonly grpc::Marshaller __Marshaller_protos_Request = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Request.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_Response = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Response.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_Push = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Push.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_BindMsg = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.BindMsg.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_KickMsg = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.KickMsg.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_KickAnswer = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.KickAnswer.Parser)); + + static readonly grpc::Method __Method_Call = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "Call", + __Marshaller_protos_Request, + __Marshaller_protos_Response); + + static readonly grpc::Method __Method_PushToUser = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "PushToUser", + __Marshaller_protos_Push, + __Marshaller_protos_Response); + + static readonly grpc::Method __Method_SessionBindRemote = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "SessionBindRemote", + __Marshaller_protos_BindMsg, + __Marshaller_protos_Response); + + static readonly grpc::Method __Method_KickUser = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "KickUser", + __Marshaller_protos_KickMsg, + __Marshaller_protos_KickAnswer); + + /// Service descriptor + public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor + { + get { return global::NPitaya.Protos.PitayaReflection.Descriptor.Services[0]; } + } + + /// Base class for server-side implementations of Pitaya + [grpc::BindServiceMethod(typeof(Pitaya), "BindService")] + public abstract partial class PitayaBase + { + public virtual global::System.Threading.Tasks.Task Call(global::NPitaya.Protos.Request request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task PushToUser(global::NPitaya.Protos.Push request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task SessionBindRemote(global::NPitaya.Protos.BindMsg request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task KickUser(global::NPitaya.Protos.KickMsg request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + } + + /// Client for Pitaya + public partial class PitayaClient : grpc::ClientBase + { + /// Creates a new client for Pitaya + /// The channel to use to make remote calls. + public PitayaClient(grpc::ChannelBase channel) : base(channel) + { + } + /// Creates a new client for Pitaya that uses a custom CallInvoker. + /// The callInvoker to use to make remote calls. + public PitayaClient(grpc::CallInvoker callInvoker) : base(callInvoker) + { + } + /// Protected parameterless constructor to allow creation of test doubles. + protected PitayaClient() : base() + { + } + /// Protected constructor to allow creation of configured clients. + /// The client configuration. + protected PitayaClient(ClientBaseConfiguration configuration) : base(configuration) + { + } + + public virtual global::NPitaya.Protos.Response Call(global::NPitaya.Protos.Request request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return Call(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Response Call(global::NPitaya.Protos.Request request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_Call, null, options, request); + } + public virtual grpc::AsyncUnaryCall CallAsync(global::NPitaya.Protos.Request request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return CallAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall CallAsync(global::NPitaya.Protos.Request request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_Call, null, options, request); + } + public virtual global::NPitaya.Protos.Response PushToUser(global::NPitaya.Protos.Push request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return PushToUser(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Response PushToUser(global::NPitaya.Protos.Push request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_PushToUser, null, options, request); + } + public virtual grpc::AsyncUnaryCall PushToUserAsync(global::NPitaya.Protos.Push request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return PushToUserAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall PushToUserAsync(global::NPitaya.Protos.Push request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_PushToUser, null, options, request); + } + public virtual global::NPitaya.Protos.Response SessionBindRemote(global::NPitaya.Protos.BindMsg request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SessionBindRemote(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Response SessionBindRemote(global::NPitaya.Protos.BindMsg request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_SessionBindRemote, null, options, request); + } + public virtual grpc::AsyncUnaryCall SessionBindRemoteAsync(global::NPitaya.Protos.BindMsg request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SessionBindRemoteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall SessionBindRemoteAsync(global::NPitaya.Protos.BindMsg request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_SessionBindRemote, null, options, request); + } + public virtual global::NPitaya.Protos.KickAnswer KickUser(global::NPitaya.Protos.KickMsg request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return KickUser(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.KickAnswer KickUser(global::NPitaya.Protos.KickMsg request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_KickUser, null, options, request); + } + public virtual grpc::AsyncUnaryCall KickUserAsync(global::NPitaya.Protos.KickMsg request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return KickUserAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall KickUserAsync(global::NPitaya.Protos.KickMsg request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_KickUser, null, options, request); + } + /// Creates a new instance of client from given ClientBaseConfiguration. + protected override PitayaClient NewInstance(ClientBaseConfiguration configuration) + { + return new PitayaClient(configuration); + } + } + + /// Creates service definition that can be registered with a server + /// An object implementing the server-side handling logic. + public static grpc::ServerServiceDefinition BindService(PitayaBase serviceImpl) + { + return grpc::ServerServiceDefinition.CreateBuilder() + .AddMethod(__Method_Call, serviceImpl.Call) + .AddMethod(__Method_PushToUser, serviceImpl.PushToUser) + .AddMethod(__Method_SessionBindRemote, serviceImpl.SessionBindRemote) + .AddMethod(__Method_KickUser, serviceImpl.KickUser).Build(); + } + + /// Register service method with a service binder with or without implementation. Useful when customizing the service binding logic. + /// Note: this method is part of an experimental API that can change or be removed without any prior notice. + /// Service methods will be bound by calling AddMethod on this object. + /// An object implementing the server-side handling logic. + public static void BindService(grpc::ServiceBinderBase serviceBinder, PitayaBase serviceImpl) + { + serviceBinder.AddMethod(__Method_Call, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.Call)); + serviceBinder.AddMethod(__Method_PushToUser, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.PushToUser)); + serviceBinder.AddMethod(__Method_SessionBindRemote, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.SessionBindRemote)); + serviceBinder.AddMethod(__Method_KickUser, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.KickUser)); + } + + } +} +#endregion diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/PitayaGrpc.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/PitayaGrpc.cs.meta new file mode 100644 index 00000000..bdd866ae --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/PitayaGrpc.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1c91f95c9842f7d4dbf4823cb0f1934f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Protodescriptor.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Protodescriptor.cs new file mode 100644 index 00000000..3a6d60b3 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Protodescriptor.cs @@ -0,0 +1,718 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: protodescriptor.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from protodescriptor.proto + public static partial class ProtodescriptorReflection { + + #region Descriptor + /// File descriptor for protodescriptor.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static ProtodescriptorReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChVwcm90b2Rlc2NyaXB0b3IucHJvdG8SBnByb3RvcyIfCg9Qcm90b0Rlc2Ny", + "aXB0b3ISDAoEZGVzYxgBIAEoDCIZCglQcm90b05hbWUSDAoEbmFtZRgBIAEo", + "CSIgChBQcm90b0Rlc2NyaXB0b3JzEgwKBGRlc2MYASADKAwiGgoKUHJvdG9O", + "YW1lcxIMCgRuYW1lGAEgAygJQjxaKWdpdGh1Yi5jb20vdG9wZnJlZWdhbWVz", + "L3BpdGF5YS9wa2cvcHJvdG9zqgIOTlBpdGF5YS5Qcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.ProtoDescriptor), global::NPitaya.Protos.ProtoDescriptor.Parser, new[]{ "Desc" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.ProtoName), global::NPitaya.Protos.ProtoName.Parser, new[]{ "Name" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.ProtoDescriptors), global::NPitaya.Protos.ProtoDescriptors.Parser, new[]{ "Desc" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.ProtoNames), global::NPitaya.Protos.ProtoNames.Parser, new[]{ "Name" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + /// + /// Descriptor proto used to retrieve zipped proto descriptors remotely + /// + public sealed partial class ProtoDescriptor : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ProtoDescriptor()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ProtodescriptorReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptor() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptor(ProtoDescriptor other) : this() { + desc_ = other.desc_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptor Clone() { + return new ProtoDescriptor(this); + } + + /// Field number for the "desc" field. + public const int DescFieldNumber = 1; + private pb::ByteString desc_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Desc { + get { return desc_; } + set { + desc_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as ProtoDescriptor); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(ProtoDescriptor other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Desc != other.Desc) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Desc.Length != 0) hash ^= Desc.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Desc.Length != 0) { + output.WriteRawTag(10); + output.WriteBytes(Desc); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Desc.Length != 0) { + output.WriteRawTag(10); + output.WriteBytes(Desc); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Desc.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Desc); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(ProtoDescriptor other) { + if (other == null) { + return; + } + if (other.Desc.Length != 0) { + Desc = other.Desc; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Desc = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Desc = input.ReadBytes(); + break; + } + } + } + } + #endif + + } + + public sealed partial class ProtoName : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ProtoName()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ProtodescriptorReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoName() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoName(ProtoName other) : this() { + name_ = other.name_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoName Clone() { + return new ProtoName(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private string name_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Name { + get { return name_; } + set { + name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as ProtoName); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(ProtoName other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(ProtoName other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Name = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Name = input.ReadString(); + break; + } + } + } + } + #endif + + } + + public sealed partial class ProtoDescriptors : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ProtoDescriptors()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ProtodescriptorReflection.Descriptor.MessageTypes[2]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptors() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptors(ProtoDescriptors other) : this() { + desc_ = other.desc_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoDescriptors Clone() { + return new ProtoDescriptors(this); + } + + /// Field number for the "desc" field. + public const int DescFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_desc_codec + = pb::FieldCodec.ForBytes(10); + private readonly pbc::RepeatedField desc_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::RepeatedField Desc { + get { return desc_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as ProtoDescriptors); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(ProtoDescriptors other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!desc_.Equals(other.desc_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + hash ^= desc_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + desc_.WriteTo(output, _repeated_desc_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + desc_.WriteTo(ref output, _repeated_desc_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + size += desc_.CalculateSize(_repeated_desc_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(ProtoDescriptors other) { + if (other == null) { + return; + } + desc_.Add(other.desc_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + desc_.AddEntriesFrom(input, _repeated_desc_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + desc_.AddEntriesFrom(ref input, _repeated_desc_codec); + break; + } + } + } + } + #endif + + } + + public sealed partial class ProtoNames : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ProtoNames()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ProtodescriptorReflection.Descriptor.MessageTypes[3]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoNames() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoNames(ProtoNames other) : this() { + name_ = other.name_.Clone(); + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ProtoNames Clone() { + return new ProtoNames(this); + } + + /// Field number for the "name" field. + public const int NameFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_name_codec + = pb::FieldCodec.ForString(10); + private readonly pbc::RepeatedField name_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::RepeatedField Name { + get { return name_; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as ProtoNames); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(ProtoNames other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!name_.Equals(other.name_)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + hash ^= name_.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + name_.WriteTo(output, _repeated_name_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + name_.WriteTo(ref output, _repeated_name_codec); + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + size += name_.CalculateSize(_repeated_name_codec); + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(ProtoNames other) { + if (other == null) { + return; + } + name_.Add(other.name_); + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + name_.AddEntriesFrom(input, _repeated_name_codec); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + name_.AddEntriesFrom(ref input, _repeated_name_codec); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Protodescriptor.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Protodescriptor.cs.meta new file mode 100644 index 00000000..c31b5a21 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Protodescriptor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 529d6ec85e3519246ab66344150a5ab5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Push.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Push.cs new file mode 100644 index 00000000..3f9f7620 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Push.cs @@ -0,0 +1,289 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: push.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from push.proto + public static partial class PushReflection { + + #region Descriptor + /// File descriptor for push.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static PushReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CgpwdXNoLnByb3RvEgZwcm90b3MiMAoEUHVzaBINCgVyb3V0ZRgBIAEoCRIL", + "CgN1aWQYAiABKAkSDAoEZGF0YRgDIAEoDEI8WilnaXRodWIuY29tL3RvcGZy", + "ZWVnYW1lcy9waXRheWEvcGtnL3Byb3Rvc6oCDk5QaXRheWEuUHJvdG9zYgZw", + "cm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Push), global::NPitaya.Protos.Push.Parser, new[]{ "Route", "Uid", "Data" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Push : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Push()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.PushReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Push() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Push(Push other) : this() { + route_ = other.route_; + uid_ = other.uid_; + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Push Clone() { + return new Push(this); + } + + /// Field number for the "route" field. + public const int RouteFieldNumber = 1; + private string route_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Route { + get { return route_; } + set { + route_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "uid" field. + public const int UidFieldNumber = 2; + private string uid_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Uid { + get { return uid_; } + set { + uid_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 3; + private pb::ByteString data_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Data { + get { return data_; } + set { + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Push); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Push other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Route != other.Route) return false; + if (Uid != other.Uid) return false; + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Route.Length != 0) hash ^= Route.GetHashCode(); + if (Uid.Length != 0) hash ^= Uid.GetHashCode(); + if (Data.Length != 0) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Route.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Route); + } + if (Uid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Uid); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Route.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Route); + } + if (Uid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Uid); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Route.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Route); + } + if (Uid.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Uid); + } + if (Data.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Push other) { + if (other == null) { + return; + } + if (other.Route.Length != 0) { + Route = other.Route; + } + if (other.Uid.Length != 0) { + Uid = other.Uid; + } + if (other.Data.Length != 0) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Route = input.ReadString(); + break; + } + case 18: { + Uid = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Route = input.ReadString(); + break; + } + case 18: { + Uid = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Push.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Push.cs.meta new file mode 100644 index 00000000..7d86f4eb --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Push.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 809c8ef06a19fb743b50ed951c729c2a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Request.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Request.cs new file mode 100644 index 00000000..fbed59f9 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Request.cs @@ -0,0 +1,390 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: request.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from request.proto + public static partial class RequestReflection { + + #region Descriptor + /// File descriptor for request.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static RequestReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cg1yZXF1ZXN0LnByb3RvEgZwcm90b3MaDXNlc3Npb24ucHJvdG8aCW1zZy5w", + "cm90byKKAQoHUmVxdWVzdBIdCgR0eXBlGAEgASgOMg8ucHJvdG9zLlJQQ1R5", + "cGUSIAoHc2Vzc2lvbhgCIAEoCzIPLnByb3Rvcy5TZXNzaW9uEhgKA21zZxgD", + "IAEoCzILLnByb3Rvcy5Nc2cSEgoKZnJvbnRlbmRJRBgEIAEoCRIQCghtZXRh", + "ZGF0YRgFIAEoDCocCgdSUENUeXBlEgcKA1N5cxAAEggKBFVzZXIQAUI8Wiln", + "aXRodWIuY29tL3RvcGZyZWVnYW1lcy9waXRheWEvcGtnL3Byb3Rvc6oCDk5Q", + "aXRheWEuUHJvdG9zYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::NPitaya.Protos.SessionReflection.Descriptor, global::NPitaya.Protos.MsgReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(new[] {typeof(global::NPitaya.Protos.RPCType), }, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Request), global::NPitaya.Protos.Request.Parser, new[]{ "Type", "Session", "Msg", "FrontendID", "Metadata" }, null, null, null, null) + })); + } + #endregion + + } + #region Enums + public enum RPCType { + [pbr::OriginalName("Sys")] Sys = 0, + [pbr::OriginalName("User")] User = 1, + } + + #endregion + + #region Messages + public sealed partial class Request : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Request()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.RequestReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Request() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Request(Request other) : this() { + type_ = other.type_; + session_ = other.session_ != null ? other.session_.Clone() : null; + msg_ = other.msg_ != null ? other.msg_.Clone() : null; + frontendID_ = other.frontendID_; + metadata_ = other.metadata_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Request Clone() { + return new Request(this); + } + + /// Field number for the "type" field. + public const int TypeFieldNumber = 1; + private global::NPitaya.Protos.RPCType type_ = global::NPitaya.Protos.RPCType.Sys; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.RPCType Type { + get { return type_; } + set { + type_ = value; + } + } + + /// Field number for the "session" field. + public const int SessionFieldNumber = 2; + private global::NPitaya.Protos.Session session_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Session Session { + get { return session_; } + set { + session_ = value; + } + } + + /// Field number for the "msg" field. + public const int MsgFieldNumber = 3; + private global::NPitaya.Protos.Msg msg_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Msg Msg { + get { return msg_; } + set { + msg_ = value; + } + } + + /// Field number for the "frontendID" field. + public const int FrontendIDFieldNumber = 4; + private string frontendID_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string FrontendID { + get { return frontendID_; } + set { + frontendID_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "metadata" field. + public const int MetadataFieldNumber = 5; + private pb::ByteString metadata_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Metadata { + get { return metadata_; } + set { + metadata_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Request); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Request other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Type != other.Type) return false; + if (!object.Equals(Session, other.Session)) return false; + if (!object.Equals(Msg, other.Msg)) return false; + if (FrontendID != other.FrontendID) return false; + if (Metadata != other.Metadata) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Type != global::NPitaya.Protos.RPCType.Sys) hash ^= Type.GetHashCode(); + if (session_ != null) hash ^= Session.GetHashCode(); + if (msg_ != null) hash ^= Msg.GetHashCode(); + if (FrontendID.Length != 0) hash ^= FrontendID.GetHashCode(); + if (Metadata.Length != 0) hash ^= Metadata.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Type != global::NPitaya.Protos.RPCType.Sys) { + output.WriteRawTag(8); + output.WriteEnum((int) Type); + } + if (session_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Session); + } + if (msg_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Msg); + } + if (FrontendID.Length != 0) { + output.WriteRawTag(34); + output.WriteString(FrontendID); + } + if (Metadata.Length != 0) { + output.WriteRawTag(42); + output.WriteBytes(Metadata); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Type != global::NPitaya.Protos.RPCType.Sys) { + output.WriteRawTag(8); + output.WriteEnum((int) Type); + } + if (session_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Session); + } + if (msg_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Msg); + } + if (FrontendID.Length != 0) { + output.WriteRawTag(34); + output.WriteString(FrontendID); + } + if (Metadata.Length != 0) { + output.WriteRawTag(42); + output.WriteBytes(Metadata); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Type != global::NPitaya.Protos.RPCType.Sys) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); + } + if (session_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Session); + } + if (msg_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Msg); + } + if (FrontendID.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FrontendID); + } + if (Metadata.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Metadata); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Request other) { + if (other == null) { + return; + } + if (other.Type != global::NPitaya.Protos.RPCType.Sys) { + Type = other.Type; + } + if (other.session_ != null) { + if (session_ == null) { + Session = new global::NPitaya.Protos.Session(); + } + Session.MergeFrom(other.Session); + } + if (other.msg_ != null) { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + Msg.MergeFrom(other.Msg); + } + if (other.FrontendID.Length != 0) { + FrontendID = other.FrontendID; + } + if (other.Metadata.Length != 0) { + Metadata = other.Metadata; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Type = (global::NPitaya.Protos.RPCType) input.ReadEnum(); + break; + } + case 18: { + if (session_ == null) { + Session = new global::NPitaya.Protos.Session(); + } + input.ReadMessage(Session); + break; + } + case 26: { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + input.ReadMessage(Msg); + break; + } + case 34: { + FrontendID = input.ReadString(); + break; + } + case 42: { + Metadata = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Type = (global::NPitaya.Protos.RPCType) input.ReadEnum(); + break; + } + case 18: { + if (session_ == null) { + Session = new global::NPitaya.Protos.Session(); + } + input.ReadMessage(Session); + break; + } + case 26: { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + input.ReadMessage(Msg); + break; + } + case 34: { + FrontendID = input.ReadString(); + break; + } + case 42: { + Metadata = input.ReadBytes(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Request.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Request.cs.meta new file mode 100644 index 00000000..fb972643 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Request.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8a975adc59606a64bbb30b18baab6bb1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Response.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Response.cs new file mode 100644 index 00000000..2882156c --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Response.cs @@ -0,0 +1,262 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: response.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from response.proto + public static partial class ResponseReflection { + + #region Descriptor + /// File descriptor for response.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static ResponseReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cg5yZXNwb25zZS5wcm90bxIGcHJvdG9zGgtlcnJvci5wcm90byI2CghSZXNw", + "b25zZRIMCgRkYXRhGAEgASgMEhwKBWVycm9yGAIgASgLMg0ucHJvdG9zLkVy", + "cm9yQjxaKWdpdGh1Yi5jb20vdG9wZnJlZWdhbWVzL3BpdGF5YS9wa2cvcHJv", + "dG9zqgIOTlBpdGF5YS5Qcm90b3NiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::NPitaya.Protos.ErrorReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Response), global::NPitaya.Protos.Response.Parser, new[]{ "Data", "Error" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Response : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Response()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.ResponseReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Response() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Response(Response other) : this() { + data_ = other.data_; + error_ = other.error_ != null ? other.error_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Response Clone() { + return new Response(this); + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 1; + private pb::ByteString data_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Data { + get { return data_; } + set { + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "error" field. + public const int ErrorFieldNumber = 2; + private global::NPitaya.Protos.Error error_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Error Error { + get { return error_; } + set { + error_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Response); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Response other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Data != other.Data) return false; + if (!object.Equals(Error, other.Error)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Data.Length != 0) hash ^= Data.GetHashCode(); + if (error_ != null) hash ^= Error.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Data.Length != 0) { + output.WriteRawTag(10); + output.WriteBytes(Data); + } + if (error_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Error); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Data.Length != 0) { + output.WriteRawTag(10); + output.WriteBytes(Data); + } + if (error_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Error); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Data.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); + } + if (error_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Error); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Response other) { + if (other == null) { + return; + } + if (other.Data.Length != 0) { + Data = other.Data; + } + if (other.error_ != null) { + if (error_ == null) { + Error = new global::NPitaya.Protos.Error(); + } + Error.MergeFrom(other.Error); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Data = input.ReadBytes(); + break; + } + case 18: { + if (error_ == null) { + Error = new global::NPitaya.Protos.Error(); + } + input.ReadMessage(Error); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Data = input.ReadBytes(); + break; + } + case 18: { + if (error_ == null) { + Error = new global::NPitaya.Protos.Error(); + } + input.ReadMessage(Error); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Response.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Response.cs.meta new file mode 100644 index 00000000..d10194dd --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Response.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4dabe5ee961ae7a478a1a8adda84c1e9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Session.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Session.cs new file mode 100644 index 00000000..7fd84830 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Session.cs @@ -0,0 +1,289 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: session.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from session.proto + public static partial class SessionReflection { + + #region Descriptor + /// File descriptor for session.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static SessionReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cg1zZXNzaW9uLnByb3RvEgZwcm90b3MiMAoHU2Vzc2lvbhIKCgJpZBgBIAEo", + "AxILCgN1aWQYAiABKAkSDAoEZGF0YRgDIAEoDEI8WilnaXRodWIuY29tL3Rv", + "cGZyZWVnYW1lcy9waXRheWEvcGtnL3Byb3Rvc6oCDk5QaXRheWEuUHJvdG9z", + "YgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Session), global::NPitaya.Protos.Session.Parser, new[]{ "Id", "Uid", "Data" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Session : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Session()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SessionReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Session() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Session(Session other) : this() { + id_ = other.id_; + uid_ = other.uid_; + data_ = other.data_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Session Clone() { + return new Session(this); + } + + /// Field number for the "id" field. + public const int IdFieldNumber = 1; + private long id_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public long Id { + get { return id_; } + set { + id_ = value; + } + } + + /// Field number for the "uid" field. + public const int UidFieldNumber = 2; + private string uid_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Uid { + get { return uid_; } + set { + uid_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "data" field. + public const int DataFieldNumber = 3; + private pb::ByteString data_ = pb::ByteString.Empty; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pb::ByteString Data { + get { return data_; } + set { + data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Session); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Session other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Id != other.Id) return false; + if (Uid != other.Uid) return false; + if (Data != other.Data) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Id != 0L) hash ^= Id.GetHashCode(); + if (Uid.Length != 0) hash ^= Uid.GetHashCode(); + if (Data.Length != 0) hash ^= Data.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Id != 0L) { + output.WriteRawTag(8); + output.WriteInt64(Id); + } + if (Uid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Uid); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Id != 0L) { + output.WriteRawTag(8); + output.WriteInt64(Id); + } + if (Uid.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Uid); + } + if (Data.Length != 0) { + output.WriteRawTag(26); + output.WriteBytes(Data); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Id != 0L) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(Id); + } + if (Uid.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Uid); + } + if (Data.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Session other) { + if (other == null) { + return; + } + if (other.Id != 0L) { + Id = other.Id; + } + if (other.Uid.Length != 0) { + Uid = other.Uid; + } + if (other.Data.Length != 0) { + Data = other.Data; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Id = input.ReadInt64(); + break; + } + case 18: { + Uid = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Id = input.ReadInt64(); + break; + } + case 18: { + Uid = input.ReadString(); + break; + } + case 26: { + Data = input.ReadBytes(); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Session.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Session.cs.meta new file mode 100644 index 00000000..4ab4c0df --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Session.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: afb9199f5edc0ae46a11a6fd5a47743f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Sidecar.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Sidecar.cs new file mode 100644 index 00000000..2f2a3323 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Sidecar.cs @@ -0,0 +1,2206 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: sidecar.proto +// +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace NPitaya.Protos { + + /// Holder for reflection information generated from sidecar.proto + public static partial class SidecarReflection { + + #region Descriptor + /// File descriptor for sidecar.proto + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static SidecarReflection() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Cg1zaWRlY2FyLnByb3RvEgZwcm90b3MaC2Vycm9yLnByb3RvGgpwdXNoLnBy", + "b3RvGgpraWNrLnByb3RvGgltc2cucHJvdG8aDnJlc3BvbnNlLnByb3RvGg1y", + "ZXF1ZXN0LnByb3RvGhtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8ipwEK", + "BlNlcnZlchIKCgJpZBgBIAEoCRIQCghmcm9udGVuZBgCIAEoCBIMCgR0eXBl", + "GAMgASgJEi4KCG1ldGFkYXRhGAQgAygLMhwucHJvdG9zLlNlcnZlci5NZXRh", + "ZGF0YUVudHJ5EhAKCGhvc3RuYW1lGAUgASgJGi8KDU1ldGFkYXRhRW50cnkS", + "CwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASJtCgdTREV2ZW50EiQK", + "BWV2ZW50GAEgASgOMhUucHJvdG9zLlNERXZlbnQuRXZlbnQSHgoGc2VydmVy", + "GAIgASgLMg4ucHJvdG9zLlNlcnZlciIcCgVFdmVudBIHCgNBREQQABIKCgZS", + "RU1PVkUQASJmChJTdGFydFBpdGF5YVJlcXVlc3QSHgoGY29uZmlnGAEgASgL", + "Mg4ucHJvdG9zLlNlcnZlchIeChZzaG91bGRDb21wcmVzc01lc3NhZ2VzGAIg", + "ASgIEhAKCGRlYnVnTG9nGAMgASgIIjcKCVJlcXVlc3RUbxIQCghzZXJ2ZXJJ", + "RBgBIAEoCRIYCgNtc2cYAiABKAsyCy5wcm90b3MuTXNnIlcKC1JQQ1Jlc3Bv", + "bnNlEg0KBXJlcUlkGAEgASgEEh0KA3JlcxgCIAEoCzIQLnByb3Rvcy5SZXNw", + "b25zZRIaCgNlcnIYAyABKAsyDS5wcm90b3MuRXJyb3IiPQoOU2lkZWNhclJl", + "cXVlc3QSDQoFcmVxSWQYASABKAQSHAoDcmVxGAIgASgLMg8ucHJvdG9zLlJl", + "cXVlc3QiPwoLUHVzaFJlcXVlc3QSFAoMZnJvbnRlbmRUeXBlGAIgASgJEhoK", + "BHB1c2gYAyABKAsyDC5wcm90b3MuUHVzaCI1CgxQdXNoUmVzcG9uc2USEgoK", + "ZmFpbGVkVWlkcxgBIAMoCRIRCgloYXNGYWlsZWQYAiABKAgiQgoLS2lja1Jl", + "cXVlc3QSFAoMZnJvbnRlbmRUeXBlGAIgASgJEh0KBGtpY2sYAyABKAsyDy5w", + "cm90b3MuS2lja01zZzL1AwoHU2lkZWNhchIrCglHZXRTZXJ2ZXISDi5wcm90", + "b3MuU2VydmVyGg4ucHJvdG9zLlNlcnZlchI7CglIZWFydGJlYXQSFi5nb29n", + "bGUucHJvdG9idWYuRW1wdHkaFi5nb29nbGUucHJvdG9idWYuRW1wdHkSPAoJ", + "TGlzdGVuUlBDEhMucHJvdG9zLlJQQ1Jlc3BvbnNlGhYucHJvdG9zLlNpZGVj", + "YXJSZXF1ZXN0KAEwARI1CghMaXN0ZW5TRBIWLmdvb2dsZS5wcm90b2J1Zi5F", + "bXB0eRoPLnByb3Rvcy5TREV2ZW50MAESLgoHU2VuZFJQQxIRLnByb3Rvcy5S", + "ZXF1ZXN0VG8aEC5wcm90b3MuUmVzcG9uc2USNQoIU2VuZFB1c2gSEy5wcm90", + "b3MuUHVzaFJlcXVlc3QaFC5wcm90b3MuUHVzaFJlc3BvbnNlEjUKCFNlbmRL", + "aWNrEhMucHJvdG9zLktpY2tSZXF1ZXN0GhQucHJvdG9zLlB1c2hSZXNwb25z", + "ZRI4CgtTdGFydFBpdGF5YRIaLnByb3Rvcy5TdGFydFBpdGF5YVJlcXVlc3Qa", + "DS5wcm90b3MuRXJyb3ISMwoKU3RvcFBpdGF5YRIWLmdvb2dsZS5wcm90b2J1", + "Zi5FbXB0eRoNLnByb3Rvcy5FcnJvckI8WilnaXRodWIuY29tL3RvcGZyZWVn", + "YW1lcy9waXRheWEvcGtnL3Byb3Rvc6oCDk5QaXRheWEuUHJvdG9zYgZwcm90", + "bzM=")); + descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, + new pbr::FileDescriptor[] { global::NPitaya.Protos.ErrorReflection.Descriptor, global::NPitaya.Protos.PushReflection.Descriptor, global::NPitaya.Protos.KickReflection.Descriptor, global::NPitaya.Protos.MsgReflection.Descriptor, global::NPitaya.Protos.ResponseReflection.Descriptor, global::NPitaya.Protos.RequestReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, }, + new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.Server), global::NPitaya.Protos.Server.Parser, new[]{ "Id", "Frontend", "Type", "Metadata", "Hostname" }, null, null, null, new pbr::GeneratedClrTypeInfo[] { null, }), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.SDEvent), global::NPitaya.Protos.SDEvent.Parser, new[]{ "Event", "Server" }, null, new[]{ typeof(global::NPitaya.Protos.SDEvent.Types.Event) }, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.StartPitayaRequest), global::NPitaya.Protos.StartPitayaRequest.Parser, new[]{ "Config", "ShouldCompressMessages", "DebugLog" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.RequestTo), global::NPitaya.Protos.RequestTo.Parser, new[]{ "ServerID", "Msg" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.RPCResponse), global::NPitaya.Protos.RPCResponse.Parser, new[]{ "ReqId", "Res", "Err" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.SidecarRequest), global::NPitaya.Protos.SidecarRequest.Parser, new[]{ "ReqId", "Req" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.PushRequest), global::NPitaya.Protos.PushRequest.Parser, new[]{ "FrontendType", "Push" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.PushResponse), global::NPitaya.Protos.PushResponse.Parser, new[]{ "FailedUids", "HasFailed" }, null, null, null, null), + new pbr::GeneratedClrTypeInfo(typeof(global::NPitaya.Protos.KickRequest), global::NPitaya.Protos.KickRequest.Parser, new[]{ "FrontendType", "Kick" }, null, null, null, null) + })); + } + #endregion + + } + #region Messages + public sealed partial class Server : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Server()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[0]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Server() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Server(Server other) : this() { + id_ = other.id_; + frontend_ = other.frontend_; + type_ = other.type_; + metadata_ = other.metadata_.Clone(); + hostname_ = other.hostname_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public Server Clone() { + return new Server(this); + } + + /// Field number for the "id" field. + public const int IdFieldNumber = 1; + private string id_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Id { + get { return id_; } + set { + id_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "frontend" field. + public const int FrontendFieldNumber = 2; + private bool frontend_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Frontend { + get { return frontend_; } + set { + frontend_ = value; + } + } + + /// Field number for the "type" field. + public const int TypeFieldNumber = 3; + private string type_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Type { + get { return type_; } + set { + type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "metadata" field. + public const int MetadataFieldNumber = 4; + private static readonly pbc::MapField.Codec _map_metadata_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 34); + private readonly pbc::MapField metadata_ = new pbc::MapField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::MapField Metadata { + get { return metadata_; } + } + + /// Field number for the "hostname" field. + public const int HostnameFieldNumber = 5; + private string hostname_ = ""; + /// + /// TODO + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string Hostname { + get { return hostname_; } + set { + hostname_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as Server); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(Server other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Id != other.Id) return false; + if (Frontend != other.Frontend) return false; + if (Type != other.Type) return false; + if (!Metadata.Equals(other.Metadata)) return false; + if (Hostname != other.Hostname) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Id.Length != 0) hash ^= Id.GetHashCode(); + if (Frontend != false) hash ^= Frontend.GetHashCode(); + if (Type.Length != 0) hash ^= Type.GetHashCode(); + hash ^= Metadata.GetHashCode(); + if (Hostname.Length != 0) hash ^= Hostname.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Id.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Id); + } + if (Frontend != false) { + output.WriteRawTag(16); + output.WriteBool(Frontend); + } + if (Type.Length != 0) { + output.WriteRawTag(26); + output.WriteString(Type); + } + metadata_.WriteTo(output, _map_metadata_codec); + if (Hostname.Length != 0) { + output.WriteRawTag(42); + output.WriteString(Hostname); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Id.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Id); + } + if (Frontend != false) { + output.WriteRawTag(16); + output.WriteBool(Frontend); + } + if (Type.Length != 0) { + output.WriteRawTag(26); + output.WriteString(Type); + } + metadata_.WriteTo(ref output, _map_metadata_codec); + if (Hostname.Length != 0) { + output.WriteRawTag(42); + output.WriteString(Hostname); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Id.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Id); + } + if (Frontend != false) { + size += 1 + 1; + } + if (Type.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Type); + } + size += metadata_.CalculateSize(_map_metadata_codec); + if (Hostname.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Hostname); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(Server other) { + if (other == null) { + return; + } + if (other.Id.Length != 0) { + Id = other.Id; + } + if (other.Frontend != false) { + Frontend = other.Frontend; + } + if (other.Type.Length != 0) { + Type = other.Type; + } + metadata_.Add(other.metadata_); + if (other.Hostname.Length != 0) { + Hostname = other.Hostname; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + Id = input.ReadString(); + break; + } + case 16: { + Frontend = input.ReadBool(); + break; + } + case 26: { + Type = input.ReadString(); + break; + } + case 34: { + metadata_.AddEntriesFrom(input, _map_metadata_codec); + break; + } + case 42: { + Hostname = input.ReadString(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + Id = input.ReadString(); + break; + } + case 16: { + Frontend = input.ReadBool(); + break; + } + case 26: { + Type = input.ReadString(); + break; + } + case 34: { + metadata_.AddEntriesFrom(ref input, _map_metadata_codec); + break; + } + case 42: { + Hostname = input.ReadString(); + break; + } + } + } + } + #endif + + } + + public sealed partial class SDEvent : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SDEvent()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[1]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SDEvent() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SDEvent(SDEvent other) : this() { + event_ = other.event_; + server_ = other.server_ != null ? other.server_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SDEvent Clone() { + return new SDEvent(this); + } + + /// Field number for the "event" field. + public const int EventFieldNumber = 1; + private global::NPitaya.Protos.SDEvent.Types.Event event_ = global::NPitaya.Protos.SDEvent.Types.Event.Add; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.SDEvent.Types.Event Event { + get { return event_; } + set { + event_ = value; + } + } + + /// Field number for the "server" field. + public const int ServerFieldNumber = 2; + private global::NPitaya.Protos.Server server_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Server Server { + get { return server_; } + set { + server_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as SDEvent); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(SDEvent other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Event != other.Event) return false; + if (!object.Equals(Server, other.Server)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (Event != global::NPitaya.Protos.SDEvent.Types.Event.Add) hash ^= Event.GetHashCode(); + if (server_ != null) hash ^= Server.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (Event != global::NPitaya.Protos.SDEvent.Types.Event.Add) { + output.WriteRawTag(8); + output.WriteEnum((int) Event); + } + if (server_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Server); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (Event != global::NPitaya.Protos.SDEvent.Types.Event.Add) { + output.WriteRawTag(8); + output.WriteEnum((int) Event); + } + if (server_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Server); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (Event != global::NPitaya.Protos.SDEvent.Types.Event.Add) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Event); + } + if (server_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Server); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(SDEvent other) { + if (other == null) { + return; + } + if (other.Event != global::NPitaya.Protos.SDEvent.Types.Event.Add) { + Event = other.Event; + } + if (other.server_ != null) { + if (server_ == null) { + Server = new global::NPitaya.Protos.Server(); + } + Server.MergeFrom(other.Server); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + Event = (global::NPitaya.Protos.SDEvent.Types.Event) input.ReadEnum(); + break; + } + case 18: { + if (server_ == null) { + Server = new global::NPitaya.Protos.Server(); + } + input.ReadMessage(Server); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + Event = (global::NPitaya.Protos.SDEvent.Types.Event) input.ReadEnum(); + break; + } + case 18: { + if (server_ == null) { + Server = new global::NPitaya.Protos.Server(); + } + input.ReadMessage(Server); + break; + } + } + } + } + #endif + + #region Nested types + /// Container for nested types declared in the SDEvent message type. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static partial class Types { + public enum Event { + [pbr::OriginalName("ADD")] Add = 0, + [pbr::OriginalName("REMOVE")] Remove = 1, + } + + } + #endregion + + } + + public sealed partial class StartPitayaRequest : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new StartPitayaRequest()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[2]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public StartPitayaRequest() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public StartPitayaRequest(StartPitayaRequest other) : this() { + config_ = other.config_ != null ? other.config_.Clone() : null; + shouldCompressMessages_ = other.shouldCompressMessages_; + debugLog_ = other.debugLog_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public StartPitayaRequest Clone() { + return new StartPitayaRequest(this); + } + + /// Field number for the "config" field. + public const int ConfigFieldNumber = 1; + private global::NPitaya.Protos.Server config_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Server Config { + get { return config_; } + set { + config_ = value; + } + } + + /// Field number for the "shouldCompressMessages" field. + public const int ShouldCompressMessagesFieldNumber = 2; + private bool shouldCompressMessages_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool ShouldCompressMessages { + get { return shouldCompressMessages_; } + set { + shouldCompressMessages_ = value; + } + } + + /// Field number for the "debugLog" field. + public const int DebugLogFieldNumber = 3; + private bool debugLog_; + /// + /// rpc module + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool DebugLog { + get { return debugLog_; } + set { + debugLog_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as StartPitayaRequest); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(StartPitayaRequest other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!object.Equals(Config, other.Config)) return false; + if (ShouldCompressMessages != other.ShouldCompressMessages) return false; + if (DebugLog != other.DebugLog) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (config_ != null) hash ^= Config.GetHashCode(); + if (ShouldCompressMessages != false) hash ^= ShouldCompressMessages.GetHashCode(); + if (DebugLog != false) hash ^= DebugLog.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (config_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Config); + } + if (ShouldCompressMessages != false) { + output.WriteRawTag(16); + output.WriteBool(ShouldCompressMessages); + } + if (DebugLog != false) { + output.WriteRawTag(24); + output.WriteBool(DebugLog); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (config_ != null) { + output.WriteRawTag(10); + output.WriteMessage(Config); + } + if (ShouldCompressMessages != false) { + output.WriteRawTag(16); + output.WriteBool(ShouldCompressMessages); + } + if (DebugLog != false) { + output.WriteRawTag(24); + output.WriteBool(DebugLog); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (config_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Config); + } + if (ShouldCompressMessages != false) { + size += 1 + 1; + } + if (DebugLog != false) { + size += 1 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(StartPitayaRequest other) { + if (other == null) { + return; + } + if (other.config_ != null) { + if (config_ == null) { + Config = new global::NPitaya.Protos.Server(); + } + Config.MergeFrom(other.Config); + } + if (other.ShouldCompressMessages != false) { + ShouldCompressMessages = other.ShouldCompressMessages; + } + if (other.DebugLog != false) { + DebugLog = other.DebugLog; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + if (config_ == null) { + Config = new global::NPitaya.Protos.Server(); + } + input.ReadMessage(Config); + break; + } + case 16: { + ShouldCompressMessages = input.ReadBool(); + break; + } + case 24: { + DebugLog = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + if (config_ == null) { + Config = new global::NPitaya.Protos.Server(); + } + input.ReadMessage(Config); + break; + } + case 16: { + ShouldCompressMessages = input.ReadBool(); + break; + } + case 24: { + DebugLog = input.ReadBool(); + break; + } + } + } + } + #endif + + } + + public sealed partial class RequestTo : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new RequestTo()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[3]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RequestTo() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RequestTo(RequestTo other) : this() { + serverID_ = other.serverID_; + msg_ = other.msg_ != null ? other.msg_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RequestTo Clone() { + return new RequestTo(this); + } + + /// Field number for the "serverID" field. + public const int ServerIDFieldNumber = 1; + private string serverID_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string ServerID { + get { return serverID_; } + set { + serverID_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "msg" field. + public const int MsgFieldNumber = 2; + private global::NPitaya.Protos.Msg msg_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Msg Msg { + get { return msg_; } + set { + msg_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as RequestTo); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(RequestTo other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (ServerID != other.ServerID) return false; + if (!object.Equals(Msg, other.Msg)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (ServerID.Length != 0) hash ^= ServerID.GetHashCode(); + if (msg_ != null) hash ^= Msg.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (ServerID.Length != 0) { + output.WriteRawTag(10); + output.WriteString(ServerID); + } + if (msg_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Msg); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (ServerID.Length != 0) { + output.WriteRawTag(10); + output.WriteString(ServerID); + } + if (msg_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Msg); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (ServerID.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(ServerID); + } + if (msg_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Msg); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(RequestTo other) { + if (other == null) { + return; + } + if (other.ServerID.Length != 0) { + ServerID = other.ServerID; + } + if (other.msg_ != null) { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + Msg.MergeFrom(other.Msg); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + ServerID = input.ReadString(); + break; + } + case 18: { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + input.ReadMessage(Msg); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + ServerID = input.ReadString(); + break; + } + case 18: { + if (msg_ == null) { + Msg = new global::NPitaya.Protos.Msg(); + } + input.ReadMessage(Msg); + break; + } + } + } + } + #endif + + } + + public sealed partial class RPCResponse : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new RPCResponse()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[4]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCResponse() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCResponse(RPCResponse other) : this() { + reqId_ = other.reqId_; + res_ = other.res_ != null ? other.res_.Clone() : null; + err_ = other.err_ != null ? other.err_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public RPCResponse Clone() { + return new RPCResponse(this); + } + + /// Field number for the "reqId" field. + public const int ReqIdFieldNumber = 1; + private ulong reqId_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ulong ReqId { + get { return reqId_; } + set { + reqId_ = value; + } + } + + /// Field number for the "res" field. + public const int ResFieldNumber = 2; + private global::NPitaya.Protos.Response res_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Response Res { + get { return res_; } + set { + res_ = value; + } + } + + /// Field number for the "err" field. + public const int ErrFieldNumber = 3; + private global::NPitaya.Protos.Error err_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Error Err { + get { return err_; } + set { + err_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as RPCResponse); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(RPCResponse other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (ReqId != other.ReqId) return false; + if (!object.Equals(Res, other.Res)) return false; + if (!object.Equals(Err, other.Err)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (ReqId != 0UL) hash ^= ReqId.GetHashCode(); + if (res_ != null) hash ^= Res.GetHashCode(); + if (err_ != null) hash ^= Err.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (ReqId != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(ReqId); + } + if (res_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Res); + } + if (err_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Err); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (ReqId != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(ReqId); + } + if (res_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Res); + } + if (err_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Err); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (ReqId != 0UL) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(ReqId); + } + if (res_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Res); + } + if (err_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Err); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(RPCResponse other) { + if (other == null) { + return; + } + if (other.ReqId != 0UL) { + ReqId = other.ReqId; + } + if (other.res_ != null) { + if (res_ == null) { + Res = new global::NPitaya.Protos.Response(); + } + Res.MergeFrom(other.Res); + } + if (other.err_ != null) { + if (err_ == null) { + Err = new global::NPitaya.Protos.Error(); + } + Err.MergeFrom(other.Err); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + ReqId = input.ReadUInt64(); + break; + } + case 18: { + if (res_ == null) { + Res = new global::NPitaya.Protos.Response(); + } + input.ReadMessage(Res); + break; + } + case 26: { + if (err_ == null) { + Err = new global::NPitaya.Protos.Error(); + } + input.ReadMessage(Err); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + ReqId = input.ReadUInt64(); + break; + } + case 18: { + if (res_ == null) { + Res = new global::NPitaya.Protos.Response(); + } + input.ReadMessage(Res); + break; + } + case 26: { + if (err_ == null) { + Err = new global::NPitaya.Protos.Error(); + } + input.ReadMessage(Err); + break; + } + } + } + } + #endif + + } + + public sealed partial class SidecarRequest : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SidecarRequest()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[5]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SidecarRequest() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SidecarRequest(SidecarRequest other) : this() { + reqId_ = other.reqId_; + req_ = other.req_ != null ? other.req_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public SidecarRequest Clone() { + return new SidecarRequest(this); + } + + /// Field number for the "reqId" field. + public const int ReqIdFieldNumber = 1; + private ulong reqId_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public ulong ReqId { + get { return reqId_; } + set { + reqId_ = value; + } + } + + /// Field number for the "req" field. + public const int ReqFieldNumber = 2; + private global::NPitaya.Protos.Request req_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Request Req { + get { return req_; } + set { + req_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as SidecarRequest); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(SidecarRequest other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (ReqId != other.ReqId) return false; + if (!object.Equals(Req, other.Req)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (ReqId != 0UL) hash ^= ReqId.GetHashCode(); + if (req_ != null) hash ^= Req.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (ReqId != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(ReqId); + } + if (req_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Req); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (ReqId != 0UL) { + output.WriteRawTag(8); + output.WriteUInt64(ReqId); + } + if (req_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Req); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (ReqId != 0UL) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(ReqId); + } + if (req_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Req); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(SidecarRequest other) { + if (other == null) { + return; + } + if (other.ReqId != 0UL) { + ReqId = other.ReqId; + } + if (other.req_ != null) { + if (req_ == null) { + Req = new global::NPitaya.Protos.Request(); + } + Req.MergeFrom(other.Req); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 8: { + ReqId = input.ReadUInt64(); + break; + } + case 18: { + if (req_ == null) { + Req = new global::NPitaya.Protos.Request(); + } + input.ReadMessage(Req); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 8: { + ReqId = input.ReadUInt64(); + break; + } + case 18: { + if (req_ == null) { + Req = new global::NPitaya.Protos.Request(); + } + input.ReadMessage(Req); + break; + } + } + } + } + #endif + + } + + public sealed partial class PushRequest : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new PushRequest()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[6]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushRequest() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushRequest(PushRequest other) : this() { + frontendType_ = other.frontendType_; + push_ = other.push_ != null ? other.push_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushRequest Clone() { + return new PushRequest(this); + } + + /// Field number for the "frontendType" field. + public const int FrontendTypeFieldNumber = 2; + private string frontendType_ = ""; + /// + /// TODO I think this field is not needed if we use nats only + /// + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string FrontendType { + get { return frontendType_; } + set { + frontendType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "push" field. + public const int PushFieldNumber = 3; + private global::NPitaya.Protos.Push push_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.Push Push { + get { return push_; } + set { + push_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as PushRequest); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(PushRequest other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (FrontendType != other.FrontendType) return false; + if (!object.Equals(Push, other.Push)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (FrontendType.Length != 0) hash ^= FrontendType.GetHashCode(); + if (push_ != null) hash ^= Push.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (FrontendType.Length != 0) { + output.WriteRawTag(18); + output.WriteString(FrontendType); + } + if (push_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Push); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (FrontendType.Length != 0) { + output.WriteRawTag(18); + output.WriteString(FrontendType); + } + if (push_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Push); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (FrontendType.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FrontendType); + } + if (push_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Push); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(PushRequest other) { + if (other == null) { + return; + } + if (other.FrontendType.Length != 0) { + FrontendType = other.FrontendType; + } + if (other.push_ != null) { + if (push_ == null) { + Push = new global::NPitaya.Protos.Push(); + } + Push.MergeFrom(other.Push); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 18: { + FrontendType = input.ReadString(); + break; + } + case 26: { + if (push_ == null) { + Push = new global::NPitaya.Protos.Push(); + } + input.ReadMessage(Push); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 18: { + FrontendType = input.ReadString(); + break; + } + case 26: { + if (push_ == null) { + Push = new global::NPitaya.Protos.Push(); + } + input.ReadMessage(Push); + break; + } + } + } + } + #endif + + } + + public sealed partial class PushResponse : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new PushResponse()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[7]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushResponse() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushResponse(PushResponse other) : this() { + failedUids_ = other.failedUids_.Clone(); + hasFailed_ = other.hasFailed_; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public PushResponse Clone() { + return new PushResponse(this); + } + + /// Field number for the "failedUids" field. + public const int FailedUidsFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_failedUids_codec + = pb::FieldCodec.ForString(10); + private readonly pbc::RepeatedField failedUids_ = new pbc::RepeatedField(); + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public pbc::RepeatedField FailedUids { + get { return failedUids_; } + } + + /// Field number for the "hasFailed" field. + public const int HasFailedFieldNumber = 2; + private bool hasFailed_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool HasFailed { + get { return hasFailed_; } + set { + hasFailed_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as PushResponse); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(PushResponse other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!failedUids_.Equals(other.failedUids_)) return false; + if (HasFailed != other.HasFailed) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + hash ^= failedUids_.GetHashCode(); + if (HasFailed != false) hash ^= HasFailed.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + failedUids_.WriteTo(output, _repeated_failedUids_codec); + if (HasFailed != false) { + output.WriteRawTag(16); + output.WriteBool(HasFailed); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + failedUids_.WriteTo(ref output, _repeated_failedUids_codec); + if (HasFailed != false) { + output.WriteRawTag(16); + output.WriteBool(HasFailed); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + size += failedUids_.CalculateSize(_repeated_failedUids_codec); + if (HasFailed != false) { + size += 1 + 1; + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(PushResponse other) { + if (other == null) { + return; + } + failedUids_.Add(other.failedUids_); + if (other.HasFailed != false) { + HasFailed = other.HasFailed; + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 10: { + failedUids_.AddEntriesFrom(input, _repeated_failedUids_codec); + break; + } + case 16: { + HasFailed = input.ReadBool(); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 10: { + failedUids_.AddEntriesFrom(ref input, _repeated_failedUids_codec); + break; + } + case 16: { + HasFailed = input.ReadBool(); + break; + } + } + } + } + #endif + + } + + public sealed partial class KickRequest : pb::IMessage + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + , pb::IBufferMessage + #endif + { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new KickRequest()); + private pb::UnknownFieldSet _unknownFields; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pb::MessageParser Parser { get { return _parser; } } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public static pbr::MessageDescriptor Descriptor { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.MessageTypes[8]; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickRequest() { + OnConstruction(); + } + + partial void OnConstruction(); + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickRequest(KickRequest other) : this() { + frontendType_ = other.frontendType_; + kick_ = other.kick_ != null ? other.kick_.Clone() : null; + _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public KickRequest Clone() { + return new KickRequest(this); + } + + /// Field number for the "frontendType" field. + public const int FrontendTypeFieldNumber = 2; + private string frontendType_ = ""; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public string FrontendType { + get { return frontendType_; } + set { + frontendType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); + } + } + + /// Field number for the "kick" field. + public const int KickFieldNumber = 3; + private global::NPitaya.Protos.KickMsg kick_; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public global::NPitaya.Protos.KickMsg Kick { + get { return kick_; } + set { + kick_ = value; + } + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override bool Equals(object other) { + return Equals(other as KickRequest); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public bool Equals(KickRequest other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (FrontendType != other.FrontendType) return false; + if (!object.Equals(Kick, other.Kick)) return false; + return Equals(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override int GetHashCode() { + int hash = 1; + if (FrontendType.Length != 0) hash ^= FrontendType.GetHashCode(); + if (kick_ != null) hash ^= Kick.GetHashCode(); + if (_unknownFields != null) { + hash ^= _unknownFields.GetHashCode(); + } + return hash; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public override string ToString() { + return pb::JsonFormatter.ToDiagnosticString(this); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void WriteTo(pb::CodedOutputStream output) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + output.WriteRawMessage(this); + #else + if (FrontendType.Length != 0) { + output.WriteRawTag(18); + output.WriteString(FrontendType); + } + if (kick_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Kick); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(output); + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { + if (FrontendType.Length != 0) { + output.WriteRawTag(18); + output.WriteString(FrontendType); + } + if (kick_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Kick); + } + if (_unknownFields != null) { + _unknownFields.WriteTo(ref output); + } + } + #endif + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public int CalculateSize() { + int size = 0; + if (FrontendType.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FrontendType); + } + if (kick_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Kick); + } + if (_unknownFields != null) { + size += _unknownFields.CalculateSize(); + } + return size; + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(KickRequest other) { + if (other == null) { + return; + } + if (other.FrontendType.Length != 0) { + FrontendType = other.FrontendType; + } + if (other.kick_ != null) { + if (kick_ == null) { + Kick = new global::NPitaya.Protos.KickMsg(); + } + Kick.MergeFrom(other.Kick); + } + _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + public void MergeFrom(pb::CodedInputStream input) { + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + input.ReadRawMessage(this); + #else + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); + break; + case 18: { + FrontendType = input.ReadString(); + break; + } + case 26: { + if (kick_ == null) { + Kick = new global::NPitaya.Protos.KickMsg(); + } + input.ReadMessage(Kick); + break; + } + } + } + #endif + } + + #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE + [global::System.Diagnostics.DebuggerNonUserCodeAttribute] + void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); + break; + case 18: { + FrontendType = input.ReadString(); + break; + } + case 26: { + if (kick_ == null) { + Kick = new global::NPitaya.Protos.KickMsg(); + } + input.ReadMessage(Kick); + break; + } + } + } + } + #endif + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Sidecar.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Sidecar.cs.meta new file mode 100644 index 00000000..38cc24eb --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/Sidecar.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1a82f8da6cfa6164585a01eaeff63ec2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/SidecarGrpc.cs b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/SidecarGrpc.cs new file mode 100644 index 00000000..d316bdaf --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/SidecarGrpc.cs @@ -0,0 +1,405 @@ +// +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: sidecar.proto +// +#pragma warning disable 0414, 1591 +#region Designer generated code + +using grpc = global::Grpc.Core; + +namespace NPitaya.Protos { + public static partial class Sidecar + { + static readonly string __ServiceName = "protos.Sidecar"; + + static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context) + { + #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION + if (message is global::Google.Protobuf.IBufferMessage) + { + context.SetPayloadLength(message.CalculateSize()); + global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter()); + context.Complete(); + return; + } + #endif + context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message)); + } + + static class __Helper_MessageCache + { + public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T)); + } + + static T __Helper_DeserializeMessage(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser parser) where T : global::Google.Protobuf.IMessage + { + #if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION + if (__Helper_MessageCache.IsBufferMessage) + { + return parser.ParseFrom(context.PayloadAsReadOnlySequence()); + } + #endif + return parser.ParseFrom(context.PayloadAsNewBuffer()); + } + + static readonly grpc::Marshaller __Marshaller_protos_Server = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Server.Parser)); + static readonly grpc::Marshaller __Marshaller_google_protobuf_Empty = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Protobuf.WellKnownTypes.Empty.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_RPCResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.RPCResponse.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_SidecarRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.SidecarRequest.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_SDEvent = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.SDEvent.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_RequestTo = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.RequestTo.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_Response = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Response.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_PushRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.PushRequest.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_PushResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.PushResponse.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_KickRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.KickRequest.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_StartPitayaRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.StartPitayaRequest.Parser)); + static readonly grpc::Marshaller __Marshaller_protos_Error = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::NPitaya.Protos.Error.Parser)); + + static readonly grpc::Method __Method_GetServer = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "GetServer", + __Marshaller_protos_Server, + __Marshaller_protos_Server); + + static readonly grpc::Method __Method_Heartbeat = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "Heartbeat", + __Marshaller_google_protobuf_Empty, + __Marshaller_google_protobuf_Empty); + + static readonly grpc::Method __Method_ListenRPC = new grpc::Method( + grpc::MethodType.DuplexStreaming, + __ServiceName, + "ListenRPC", + __Marshaller_protos_RPCResponse, + __Marshaller_protos_SidecarRequest); + + static readonly grpc::Method __Method_ListenSD = new grpc::Method( + grpc::MethodType.ServerStreaming, + __ServiceName, + "ListenSD", + __Marshaller_google_protobuf_Empty, + __Marshaller_protos_SDEvent); + + static readonly grpc::Method __Method_SendRPC = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "SendRPC", + __Marshaller_protos_RequestTo, + __Marshaller_protos_Response); + + static readonly grpc::Method __Method_SendPush = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "SendPush", + __Marshaller_protos_PushRequest, + __Marshaller_protos_PushResponse); + + static readonly grpc::Method __Method_SendKick = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "SendKick", + __Marshaller_protos_KickRequest, + __Marshaller_protos_PushResponse); + + static readonly grpc::Method __Method_StartPitaya = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "StartPitaya", + __Marshaller_protos_StartPitayaRequest, + __Marshaller_protos_Error); + + static readonly grpc::Method __Method_StopPitaya = new grpc::Method( + grpc::MethodType.Unary, + __ServiceName, + "StopPitaya", + __Marshaller_google_protobuf_Empty, + __Marshaller_protos_Error); + + /// Service descriptor + public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor + { + get { return global::NPitaya.Protos.SidecarReflection.Descriptor.Services[0]; } + } + + /// Base class for server-side implementations of Sidecar + [grpc::BindServiceMethod(typeof(Sidecar), "BindService")] + public abstract partial class SidecarBase + { + public virtual global::System.Threading.Tasks.Task GetServer(global::NPitaya.Protos.Server request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task Heartbeat(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task ListenRPC(grpc::IAsyncStreamReader requestStream, grpc::IServerStreamWriter responseStream, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task ListenSD(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::IServerStreamWriter responseStream, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task SendRPC(global::NPitaya.Protos.RequestTo request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task SendPush(global::NPitaya.Protos.PushRequest request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task SendKick(global::NPitaya.Protos.KickRequest request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + public virtual global::System.Threading.Tasks.Task StartPitaya(global::NPitaya.Protos.StartPitayaRequest request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + /// + /// AddRoute + /// + /// The request received from the client. + /// The context of the server-side call handler being invoked. + /// The response to send back to the client (wrapped by a task). + public virtual global::System.Threading.Tasks.Task StopPitaya(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) + { + throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); + } + + } + + /// Client for Sidecar + public partial class SidecarClient : grpc::ClientBase + { + /// Creates a new client for Sidecar + /// The channel to use to make remote calls. + public SidecarClient(grpc::ChannelBase channel) : base(channel) + { + } + /// Creates a new client for Sidecar that uses a custom CallInvoker. + /// The callInvoker to use to make remote calls. + public SidecarClient(grpc::CallInvoker callInvoker) : base(callInvoker) + { + } + /// Protected parameterless constructor to allow creation of test doubles. + protected SidecarClient() : base() + { + } + /// Protected constructor to allow creation of configured clients. + /// The client configuration. + protected SidecarClient(ClientBaseConfiguration configuration) : base(configuration) + { + } + + public virtual global::NPitaya.Protos.Server GetServer(global::NPitaya.Protos.Server request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return GetServer(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Server GetServer(global::NPitaya.Protos.Server request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_GetServer, null, options, request); + } + public virtual grpc::AsyncUnaryCall GetServerAsync(global::NPitaya.Protos.Server request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return GetServerAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall GetServerAsync(global::NPitaya.Protos.Server request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_GetServer, null, options, request); + } + public virtual global::Google.Protobuf.WellKnownTypes.Empty Heartbeat(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return Heartbeat(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::Google.Protobuf.WellKnownTypes.Empty Heartbeat(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_Heartbeat, null, options, request); + } + public virtual grpc::AsyncUnaryCall HeartbeatAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return HeartbeatAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall HeartbeatAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_Heartbeat, null, options, request); + } + public virtual grpc::AsyncDuplexStreamingCall ListenRPC(grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return ListenRPC(new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncDuplexStreamingCall ListenRPC(grpc::CallOptions options) + { + return CallInvoker.AsyncDuplexStreamingCall(__Method_ListenRPC, null, options); + } + public virtual grpc::AsyncServerStreamingCall ListenSD(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return ListenSD(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncServerStreamingCall ListenSD(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) + { + return CallInvoker.AsyncServerStreamingCall(__Method_ListenSD, null, options, request); + } + public virtual global::NPitaya.Protos.Response SendRPC(global::NPitaya.Protos.RequestTo request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendRPC(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Response SendRPC(global::NPitaya.Protos.RequestTo request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_SendRPC, null, options, request); + } + public virtual grpc::AsyncUnaryCall SendRPCAsync(global::NPitaya.Protos.RequestTo request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendRPCAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall SendRPCAsync(global::NPitaya.Protos.RequestTo request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_SendRPC, null, options, request); + } + public virtual global::NPitaya.Protos.PushResponse SendPush(global::NPitaya.Protos.PushRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendPush(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.PushResponse SendPush(global::NPitaya.Protos.PushRequest request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_SendPush, null, options, request); + } + public virtual grpc::AsyncUnaryCall SendPushAsync(global::NPitaya.Protos.PushRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendPushAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall SendPushAsync(global::NPitaya.Protos.PushRequest request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_SendPush, null, options, request); + } + public virtual global::NPitaya.Protos.PushResponse SendKick(global::NPitaya.Protos.KickRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendKick(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.PushResponse SendKick(global::NPitaya.Protos.KickRequest request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_SendKick, null, options, request); + } + public virtual grpc::AsyncUnaryCall SendKickAsync(global::NPitaya.Protos.KickRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return SendKickAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall SendKickAsync(global::NPitaya.Protos.KickRequest request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_SendKick, null, options, request); + } + public virtual global::NPitaya.Protos.Error StartPitaya(global::NPitaya.Protos.StartPitayaRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return StartPitaya(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual global::NPitaya.Protos.Error StartPitaya(global::NPitaya.Protos.StartPitayaRequest request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_StartPitaya, null, options, request); + } + public virtual grpc::AsyncUnaryCall StartPitayaAsync(global::NPitaya.Protos.StartPitayaRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return StartPitayaAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + public virtual grpc::AsyncUnaryCall StartPitayaAsync(global::NPitaya.Protos.StartPitayaRequest request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_StartPitaya, null, options, request); + } + /// + /// AddRoute + /// + /// The request to send to the server. + /// The initial metadata to send with the call. This parameter is optional. + /// An optional deadline for the call. The call will be cancelled if deadline is hit. + /// An optional token for canceling the call. + /// The response received from the server. + public virtual global::NPitaya.Protos.Error StopPitaya(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return StopPitaya(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + /// + /// AddRoute + /// + /// The request to send to the server. + /// The options for the call. + /// The response received from the server. + public virtual global::NPitaya.Protos.Error StopPitaya(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) + { + return CallInvoker.BlockingUnaryCall(__Method_StopPitaya, null, options, request); + } + /// + /// AddRoute + /// + /// The request to send to the server. + /// The initial metadata to send with the call. This parameter is optional. + /// An optional deadline for the call. The call will be cancelled if deadline is hit. + /// An optional token for canceling the call. + /// The call object. + public virtual grpc::AsyncUnaryCall StopPitayaAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) + { + return StopPitayaAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); + } + /// + /// AddRoute + /// + /// The request to send to the server. + /// The options for the call. + /// The call object. + public virtual grpc::AsyncUnaryCall StopPitayaAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) + { + return CallInvoker.AsyncUnaryCall(__Method_StopPitaya, null, options, request); + } + /// Creates a new instance of client from given ClientBaseConfiguration. + protected override SidecarClient NewInstance(ClientBaseConfiguration configuration) + { + return new SidecarClient(configuration); + } + } + + /// Creates service definition that can be registered with a server + /// An object implementing the server-side handling logic. + public static grpc::ServerServiceDefinition BindService(SidecarBase serviceImpl) + { + return grpc::ServerServiceDefinition.CreateBuilder() + .AddMethod(__Method_GetServer, serviceImpl.GetServer) + .AddMethod(__Method_Heartbeat, serviceImpl.Heartbeat) + .AddMethod(__Method_ListenRPC, serviceImpl.ListenRPC) + .AddMethod(__Method_ListenSD, serviceImpl.ListenSD) + .AddMethod(__Method_SendRPC, serviceImpl.SendRPC) + .AddMethod(__Method_SendPush, serviceImpl.SendPush) + .AddMethod(__Method_SendKick, serviceImpl.SendKick) + .AddMethod(__Method_StartPitaya, serviceImpl.StartPitaya) + .AddMethod(__Method_StopPitaya, serviceImpl.StopPitaya).Build(); + } + + /// Register service method with a service binder with or without implementation. Useful when customizing the service binding logic. + /// Note: this method is part of an experimental API that can change or be removed without any prior notice. + /// Service methods will be bound by calling AddMethod on this object. + /// An object implementing the server-side handling logic. + public static void BindService(grpc::ServiceBinderBase serviceBinder, SidecarBase serviceImpl) + { + serviceBinder.AddMethod(__Method_GetServer, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.GetServer)); + serviceBinder.AddMethod(__Method_Heartbeat, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.Heartbeat)); + serviceBinder.AddMethod(__Method_ListenRPC, serviceImpl == null ? null : new grpc::DuplexStreamingServerMethod(serviceImpl.ListenRPC)); + serviceBinder.AddMethod(__Method_ListenSD, serviceImpl == null ? null : new grpc::ServerStreamingServerMethod(serviceImpl.ListenSD)); + serviceBinder.AddMethod(__Method_SendRPC, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.SendRPC)); + serviceBinder.AddMethod(__Method_SendPush, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.SendPush)); + serviceBinder.AddMethod(__Method_SendKick, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.SendKick)); + serviceBinder.AddMethod(__Method_StartPitaya, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.StartPitaya)); + serviceBinder.AddMethod(__Method_StopPitaya, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.StopPitaya)); + } + + } +} +#endregion diff --git a/csharp/examples/unity/Assets/Scripts/NPitaya/gen/SidecarGrpc.cs.meta b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/SidecarGrpc.cs.meta new file mode 100644 index 00000000..d0dc81e6 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/NPitaya/gen/SidecarGrpc.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3f5109e177e0c9141b5b75d22f3beb22 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/Scripts/UnityExample.cs b/csharp/examples/unity/Assets/Scripts/UnityExample.cs new file mode 100644 index 00000000..89f12584 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/UnityExample.cs @@ -0,0 +1,74 @@ +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UI; +using NPitaya; +using System; + +public class UnityExample : MonoBehaviour +{ + public Button startBtn; + public Button terminateBtn; + // Start is called before the first frame update + void Start() + { + startBtn.onClick.AddListener(OnStartClick); + terminateBtn.onClick.AddListener(OnTerminateClick); + } + + void MyLog(NPitaya.Models.LogLevel level, string message, params object[] objs){ + Debug.Log("Hello focking: " + message); + } + + void OnApplicationQuit() + { + Debug.Log("Application ending after " + Time.time + " seconds"); + PitayaCluster.Terminate(); + } + void OnTerminateClick(){ + PitayaCluster.Terminate(); + } + void OnStartClick() + { + NPitaya.Models.Logger.SetLevel(NPitaya.Models.LogLevel.DEBUG); + string serverId = System.Guid.NewGuid().ToString(); + var metadata = new Dictionary(){ + {"testKey", "testValue"} + }; + + var sv = new NPitaya.Protos.Server + { + Id = serverId, + Type = "csharp", + Hostname = "localhost", + Frontend = false + }; + sv.Metadata.Add(metadata); + + Debug.Log("Will initialize pitaya"); + PitayaCluster.SetSerializer(new NPitaya.Serializer.JSONSerializer()); + PitayaCluster.Initialize( + "localhost", + 5000, + sv, + true, + (sdEvent) => + { + switch (sdEvent.Event) + { + case NPitaya.Protos.SDEvent.Types.Event.Add: + Debug.Log("Server was added"); + Debug.Log(" id: " + sdEvent.Server.Id); + Debug.Log(" type: " + sdEvent.Server.Type); + break; + case NPitaya.Protos.SDEvent.Types.Event.Remove: + Debug.Log("Server was removed"); + Debug.Log(" id: " + sdEvent.Server.Id); + Debug.Log(" type: " + sdEvent.Server.Type); + break; + default: + throw new ArgumentOutOfRangeException(nameof(sdEvent.Event), sdEvent.Event, null); + } + } + ); + } +} diff --git a/csharp/examples/unity/Assets/Scripts/UnityExample.cs.meta b/csharp/examples/unity/Assets/Scripts/UnityExample.cs.meta new file mode 100644 index 00000000..e761d0d2 --- /dev/null +++ b/csharp/examples/unity/Assets/Scripts/UnityExample.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 97dfcc7c063aea94c9e6cb41b2fcd3f5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Assets/packages.config b/csharp/examples/unity/Assets/packages.config new file mode 100644 index 00000000..73026c10 --- /dev/null +++ b/csharp/examples/unity/Assets/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/csharp/examples/unity/Assets/packages.config.meta b/csharp/examples/unity/Assets/packages.config.meta new file mode 100644 index 00000000..bca0497a --- /dev/null +++ b/csharp/examples/unity/Assets/packages.config.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: 14cc284b730cc4d4b82f0636dcf308fa +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + Windows Store Apps: WindowsStoreApps + second: + enabled: 0 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/csharp/examples/unity/Packages/manifest.json b/csharp/examples/unity/Packages/manifest.json new file mode 100644 index 00000000..818bc2a1 --- /dev/null +++ b/csharp/examples/unity/Packages/manifest.json @@ -0,0 +1,49 @@ +{ + "dependencies": { + "com.unity.2d.animation": "3.2.9", + "com.unity.2d.pixel-perfect": "2.1.0", + "com.unity.2d.psdimporter": "2.1.8", + "com.unity.2d.sprite": "1.0.0", + "com.unity.2d.spriteshape": "3.0.16", + "com.unity.2d.tilemap": "1.0.0", + "com.unity.collab-proxy": "1.6.0", + "com.unity.ide.rider": "1.2.1", + "com.unity.ide.visualstudio": "2.0.9", + "com.unity.ide.vscode": "1.2.3", + "com.unity.test-framework": "1.1.27", + "com.unity.textmeshpro": "2.1.6", + "com.unity.timeline": "1.2.18", + "com.unity.ugui": "1.0.0", + "com.unity.modules.ai": "1.0.0", + "com.unity.modules.androidjni": "1.0.0", + "com.unity.modules.animation": "1.0.0", + "com.unity.modules.assetbundle": "1.0.0", + "com.unity.modules.audio": "1.0.0", + "com.unity.modules.cloth": "1.0.0", + "com.unity.modules.director": "1.0.0", + "com.unity.modules.imageconversion": "1.0.0", + "com.unity.modules.imgui": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0", + "com.unity.modules.particlesystem": "1.0.0", + "com.unity.modules.physics": "1.0.0", + "com.unity.modules.physics2d": "1.0.0", + "com.unity.modules.screencapture": "1.0.0", + "com.unity.modules.terrain": "1.0.0", + "com.unity.modules.terrainphysics": "1.0.0", + "com.unity.modules.tilemap": "1.0.0", + "com.unity.modules.ui": "1.0.0", + "com.unity.modules.uielements": "1.0.0", + "com.unity.modules.umbra": "1.0.0", + "com.unity.modules.unityanalytics": "1.0.0", + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.modules.unitywebrequestassetbundle": "1.0.0", + "com.unity.modules.unitywebrequestaudio": "1.0.0", + "com.unity.modules.unitywebrequesttexture": "1.0.0", + "com.unity.modules.unitywebrequestwww": "1.0.0", + "com.unity.modules.vehicles": "1.0.0", + "com.unity.modules.video": "1.0.0", + "com.unity.modules.vr": "1.0.0", + "com.unity.modules.wind": "1.0.0", + "com.unity.modules.xr": "1.0.0" + } +} diff --git a/csharp/examples/unity/Packages/packages-lock.json b/csharp/examples/unity/Packages/packages-lock.json new file mode 100644 index 00000000..43def8a6 --- /dev/null +++ b/csharp/examples/unity/Packages/packages-lock.json @@ -0,0 +1,404 @@ +{ + "dependencies": { + "com.unity.2d.animation": { + "version": "3.2.9", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.2d.common": "2.1.0", + "com.unity.mathematics": "1.1.0", + "com.unity.2d.sprite": "1.0.0", + "com.unity.modules.animation": "1.0.0", + "com.unity.modules.uielements": "1.0.0" + }, + "url": "https://packages.unity.com" + }, + "com.unity.2d.common": { + "version": "2.1.0", + "depth": 1, + "source": "registry", + "dependencies": { + "com.unity.2d.sprite": "1.0.0", + "com.unity.modules.uielements": "1.0.0" + }, + "url": "https://packages.unity.com" + }, + "com.unity.2d.path": { + "version": "2.1.0", + "depth": 1, + "source": "registry", + "dependencies": {}, + "url": "https://packages.unity.com" + }, + "com.unity.2d.pixel-perfect": { + "version": "2.1.0", + "depth": 0, + "source": "registry", + "dependencies": {}, + "url": "https://packages.unity.com" + }, + "com.unity.2d.psdimporter": { + "version": "2.1.8", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.2d.common": "2.1.0", + "com.unity.2d.animation": "3.2.9", + "com.unity.2d.sprite": "1.0.0" + }, + "url": "https://packages.unity.com" + }, + "com.unity.2d.sprite": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.2d.spriteshape": { + "version": "3.0.16", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.mathematics": "1.1.0", + "com.unity.2d.common": "2.1.0", + "com.unity.2d.path": "2.1.0" + }, + "url": "https://packages.unity.com" + }, + "com.unity.2d.tilemap": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.collab-proxy": { + "version": "1.6.0", + "depth": 0, + "source": "registry", + "dependencies": {}, + "url": "https://packages.unity.com" + }, + "com.unity.ext.nunit": { + "version": "1.0.6", + "depth": 1, + "source": "registry", + "dependencies": {}, + "url": "https://packages.unity.com" + }, + "com.unity.ide.rider": { + "version": "1.2.1", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.test-framework": "1.1.1" + }, + "url": "https://packages.unity.com" + }, + "com.unity.ide.visualstudio": { + "version": "2.0.9", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.test-framework": "1.1.9" + }, + "url": "https://packages.unity.com" + }, + "com.unity.ide.vscode": { + "version": "1.2.3", + "depth": 0, + "source": "registry", + "dependencies": {}, + "url": "https://packages.unity.com" + }, + "com.unity.mathematics": { + "version": "1.1.0", + "depth": 1, + "source": "registry", + "dependencies": {}, + "url": "https://packages.unity.com" + }, + "com.unity.test-framework": { + "version": "1.1.27", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.ext.nunit": "1.0.6", + "com.unity.modules.imgui": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0" + }, + "url": "https://packages.unity.com" + }, + "com.unity.textmeshpro": { + "version": "2.1.6", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.ugui": "1.0.0" + }, + "url": "https://packages.unity.com" + }, + "com.unity.timeline": { + "version": "1.2.18", + "depth": 0, + "source": "registry", + "dependencies": { + "com.unity.modules.director": "1.0.0", + "com.unity.modules.animation": "1.0.0", + "com.unity.modules.audio": "1.0.0", + "com.unity.modules.particlesystem": "1.0.0" + }, + "url": "https://packages.unity.com" + }, + "com.unity.ugui": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.ui": "1.0.0", + "com.unity.modules.imgui": "1.0.0" + } + }, + "com.unity.modules.ai": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.androidjni": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.animation": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.assetbundle": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.audio": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.cloth": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.physics": "1.0.0" + } + }, + "com.unity.modules.director": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.audio": "1.0.0", + "com.unity.modules.animation": "1.0.0" + } + }, + "com.unity.modules.imageconversion": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.imgui": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.jsonserialize": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.particlesystem": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.physics": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.physics2d": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.screencapture": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.imageconversion": "1.0.0" + } + }, + "com.unity.modules.subsystems": { + "version": "1.0.0", + "depth": 1, + "source": "builtin", + "dependencies": { + "com.unity.modules.jsonserialize": "1.0.0" + } + }, + "com.unity.modules.terrain": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.terrainphysics": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.physics": "1.0.0", + "com.unity.modules.terrain": "1.0.0" + } + }, + "com.unity.modules.tilemap": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.physics2d": "1.0.0" + } + }, + "com.unity.modules.ui": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.uielements": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.imgui": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0" + } + }, + "com.unity.modules.umbra": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.unityanalytics": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0" + } + }, + "com.unity.modules.unitywebrequest": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.unitywebrequestassetbundle": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.assetbundle": "1.0.0", + "com.unity.modules.unitywebrequest": "1.0.0" + } + }, + "com.unity.modules.unitywebrequestaudio": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.modules.audio": "1.0.0" + } + }, + "com.unity.modules.unitywebrequesttexture": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.modules.imageconversion": "1.0.0" + } + }, + "com.unity.modules.unitywebrequestwww": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.unitywebrequest": "1.0.0", + "com.unity.modules.unitywebrequestassetbundle": "1.0.0", + "com.unity.modules.unitywebrequestaudio": "1.0.0", + "com.unity.modules.audio": "1.0.0", + "com.unity.modules.assetbundle": "1.0.0", + "com.unity.modules.imageconversion": "1.0.0" + } + }, + "com.unity.modules.vehicles": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.physics": "1.0.0" + } + }, + "com.unity.modules.video": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.audio": "1.0.0", + "com.unity.modules.ui": "1.0.0", + "com.unity.modules.unitywebrequest": "1.0.0" + } + }, + "com.unity.modules.vr": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.jsonserialize": "1.0.0", + "com.unity.modules.physics": "1.0.0", + "com.unity.modules.xr": "1.0.0" + } + }, + "com.unity.modules.wind": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": {} + }, + "com.unity.modules.xr": { + "version": "1.0.0", + "depth": 0, + "source": "builtin", + "dependencies": { + "com.unity.modules.physics": "1.0.0", + "com.unity.modules.jsonserialize": "1.0.0", + "com.unity.modules.subsystems": "1.0.0" + } + } + } +} diff --git a/csharp/examples/unity/ProjectSettings/AudioManager.asset b/csharp/examples/unity/ProjectSettings/AudioManager.asset new file mode 100644 index 00000000..07ebfb05 --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/AudioManager.asset @@ -0,0 +1,19 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!11 &1 +AudioManager: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Volume: 1 + Rolloff Scale: 1 + Doppler Factor: 1 + Default Speaker Mode: 2 + m_SampleRate: 0 + m_DSPBufferSize: 1024 + m_VirtualVoiceCount: 512 + m_RealVoiceCount: 32 + m_SpatializerPlugin: + m_AmbisonicDecoderPlugin: + m_DisableAudio: 0 + m_VirtualizeEffects: 1 + m_RequestedDSPBufferSize: 1024 diff --git a/csharp/examples/unity/ProjectSettings/ClusterInputManager.asset b/csharp/examples/unity/ProjectSettings/ClusterInputManager.asset new file mode 100644 index 00000000..e7886b26 --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/ClusterInputManager.asset @@ -0,0 +1,6 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!236 &1 +ClusterInputManager: + m_ObjectHideFlags: 0 + m_Inputs: [] diff --git a/csharp/examples/unity/ProjectSettings/DynamicsManager.asset b/csharp/examples/unity/ProjectSettings/DynamicsManager.asset new file mode 100644 index 00000000..cdc1f3ea --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/DynamicsManager.asset @@ -0,0 +1,34 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!55 &1 +PhysicsManager: + m_ObjectHideFlags: 0 + serializedVersion: 11 + m_Gravity: {x: 0, y: -9.81, z: 0} + m_DefaultMaterial: {fileID: 0} + m_BounceThreshold: 2 + m_SleepThreshold: 0.005 + m_DefaultContactOffset: 0.01 + m_DefaultSolverIterations: 6 + m_DefaultSolverVelocityIterations: 1 + m_QueriesHitBackfaces: 0 + m_QueriesHitTriggers: 1 + m_EnableAdaptiveForce: 0 + m_ClothInterCollisionDistance: 0 + m_ClothInterCollisionStiffness: 0 + m_ContactsGeneration: 1 + m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff + m_AutoSimulation: 1 + m_AutoSyncTransforms: 0 + m_ReuseCollisionCallbacks: 1 + m_ClothInterCollisionSettingsToggle: 0 + m_ContactPairsMode: 0 + m_BroadphaseType: 0 + m_WorldBounds: + m_Center: {x: 0, y: 0, z: 0} + m_Extent: {x: 250, y: 250, z: 250} + m_WorldSubdivisions: 8 + m_FrictionType: 0 + m_EnableEnhancedDeterminism: 0 + m_EnableUnifiedHeightmaps: 1 + m_DefaultMaxAngluarSpeed: 7 diff --git a/csharp/examples/unity/ProjectSettings/EditorBuildSettings.asset b/csharp/examples/unity/ProjectSettings/EditorBuildSettings.asset new file mode 100644 index 00000000..0147887e --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/EditorBuildSettings.asset @@ -0,0 +1,8 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1045 &1 +EditorBuildSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Scenes: [] + m_configObjects: {} diff --git a/csharp/examples/unity/ProjectSettings/EditorSettings.asset b/csharp/examples/unity/ProjectSettings/EditorSettings.asset new file mode 100644 index 00000000..5a7387fa --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/EditorSettings.asset @@ -0,0 +1,35 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!159 &1 +EditorSettings: + m_ObjectHideFlags: 0 + serializedVersion: 9 + m_ExternalVersionControlSupport: Visible Meta Files + m_SerializationMode: 2 + m_LineEndingsForNewScripts: 0 + m_DefaultBehaviorMode: 1 + m_PrefabRegularEnvironment: {fileID: 0} + m_PrefabUIEnvironment: {fileID: 0} + m_SpritePackerMode: 4 + m_SpritePackerPaddingPower: 1 + m_EtcTextureCompressorBehavior: 1 + m_EtcTextureFastCompressor: 1 + m_EtcTextureNormalCompressor: 2 + m_EtcTextureBestCompressor: 4 + m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd;asmdef;rsp;asmref + m_ProjectGenerationRootNamespace: + m_CollabEditorSettings: + inProgressEnabled: 1 + m_EnableTextureStreamingInEditMode: 1 + m_EnableTextureStreamingInPlayMode: 1 + m_AsyncShaderCompilation: 1 + m_EnterPlayModeOptionsEnabled: 0 + m_EnterPlayModeOptions: 3 + m_ShowLightmapResolutionOverlay: 1 + m_UseLegacyProbeSampleCount: 1 + m_AssetPipelineMode: 1 + m_CacheServerMode: 0 + m_CacheServerEndpoint: + m_CacheServerNamespacePrefix: default + m_CacheServerEnableDownload: 1 + m_CacheServerEnableUpload: 1 diff --git a/csharp/examples/unity/ProjectSettings/GraphicsSettings.asset b/csharp/examples/unity/ProjectSettings/GraphicsSettings.asset new file mode 100644 index 00000000..6c2632ad --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/GraphicsSettings.asset @@ -0,0 +1,57 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!30 &1 +GraphicsSettings: + m_ObjectHideFlags: 0 + serializedVersion: 12 + m_Deferred: + m_Mode: 1 + m_Shader: {fileID: 69, guid: 0000000000000000f000000000000000, type: 0} + m_DeferredReflections: + m_Mode: 1 + m_Shader: {fileID: 74, guid: 0000000000000000f000000000000000, type: 0} + m_ScreenSpaceShadows: + m_Mode: 1 + m_Shader: {fileID: 64, guid: 0000000000000000f000000000000000, type: 0} + m_LegacyDeferred: + m_Mode: 1 + m_Shader: {fileID: 63, guid: 0000000000000000f000000000000000, type: 0} + m_DepthNormals: + m_Mode: 1 + m_Shader: {fileID: 62, guid: 0000000000000000f000000000000000, type: 0} + m_MotionVectors: + m_Mode: 1 + m_Shader: {fileID: 75, guid: 0000000000000000f000000000000000, type: 0} + m_LightHalo: + m_Mode: 1 + m_Shader: {fileID: 105, guid: 0000000000000000f000000000000000, type: 0} + m_LensFlare: + m_Mode: 1 + m_Shader: {fileID: 102, guid: 0000000000000000f000000000000000, type: 0} + m_AlwaysIncludedShaders: + - {fileID: 10753, guid: 0000000000000000f000000000000000, type: 0} + - {fileID: 10770, guid: 0000000000000000f000000000000000, type: 0} + m_PreloadedShaders: [] + m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000, + type: 0} + m_CustomRenderPipeline: {fileID: 0} + m_TransparencySortMode: 0 + m_TransparencySortAxis: {x: 0, y: 0, z: 1} + m_DefaultRenderingPath: 1 + m_DefaultMobileRenderingPath: 1 + m_TierSettings: [] + m_LightmapStripping: 0 + m_FogStripping: 0 + m_InstancingStripping: 0 + m_LightmapKeepPlain: 1 + m_LightmapKeepDirCombined: 1 + m_LightmapKeepDynamicPlain: 1 + m_LightmapKeepDynamicDirCombined: 1 + m_LightmapKeepShadowMask: 1 + m_LightmapKeepSubtractive: 1 + m_FogKeepLinear: 1 + m_FogKeepExp: 1 + m_FogKeepExp2: 1 + m_AlbedoSwatchInfos: [] + m_LightsUseLinearIntensity: 0 + m_LightsUseColorTemperature: 0 diff --git a/csharp/examples/unity/ProjectSettings/InputManager.asset b/csharp/examples/unity/ProjectSettings/InputManager.asset new file mode 100644 index 00000000..17c8f538 --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/InputManager.asset @@ -0,0 +1,295 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!13 &1 +InputManager: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_Axes: + - serializedVersion: 3 + m_Name: Horizontal + descriptiveName: + descriptiveNegativeName: + negativeButton: left + positiveButton: right + altNegativeButton: a + altPositiveButton: d + gravity: 3 + dead: 0.001 + sensitivity: 3 + snap: 1 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Vertical + descriptiveName: + descriptiveNegativeName: + negativeButton: down + positiveButton: up + altNegativeButton: s + altPositiveButton: w + gravity: 3 + dead: 0.001 + sensitivity: 3 + snap: 1 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire1 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left ctrl + altNegativeButton: + altPositiveButton: mouse 0 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire2 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left alt + altNegativeButton: + altPositiveButton: mouse 1 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire3 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: left shift + altNegativeButton: + altPositiveButton: mouse 2 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Jump + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: space + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse X + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse Y + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 1 + joyNum: 0 + - serializedVersion: 3 + m_Name: Mouse ScrollWheel + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0 + sensitivity: 0.1 + snap: 0 + invert: 0 + type: 1 + axis: 2 + joyNum: 0 + - serializedVersion: 3 + m_Name: Horizontal + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0.19 + sensitivity: 1 + snap: 0 + invert: 0 + type: 2 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Vertical + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: + altNegativeButton: + altPositiveButton: + gravity: 0 + dead: 0.19 + sensitivity: 1 + snap: 0 + invert: 1 + type: 2 + axis: 1 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire1 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 0 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire2 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 1 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Fire3 + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 2 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Jump + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: joystick button 3 + altNegativeButton: + altPositiveButton: + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Submit + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: return + altNegativeButton: + altPositiveButton: joystick button 0 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Submit + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: enter + altNegativeButton: + altPositiveButton: space + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 + - serializedVersion: 3 + m_Name: Cancel + descriptiveName: + descriptiveNegativeName: + negativeButton: + positiveButton: escape + altNegativeButton: + altPositiveButton: joystick button 1 + gravity: 1000 + dead: 0.001 + sensitivity: 1000 + snap: 0 + invert: 0 + type: 0 + axis: 0 + joyNum: 0 diff --git a/csharp/examples/unity/ProjectSettings/NavMeshAreas.asset b/csharp/examples/unity/ProjectSettings/NavMeshAreas.asset new file mode 100644 index 00000000..3b0b7c3d --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/NavMeshAreas.asset @@ -0,0 +1,91 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!126 &1 +NavMeshProjectSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + areas: + - name: Walkable + cost: 1 + - name: Not Walkable + cost: 1 + - name: Jump + cost: 2 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + - name: + cost: 1 + m_LastAgentTypeID: -887442657 + m_Settings: + - serializedVersion: 2 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.75 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + accuratePlacement: 0 + debug: + m_Flags: 0 + m_SettingNames: + - Humanoid diff --git a/csharp/examples/unity/ProjectSettings/NetworkManager.asset b/csharp/examples/unity/ProjectSettings/NetworkManager.asset new file mode 100644 index 00000000..5dc6a831 --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/NetworkManager.asset @@ -0,0 +1,8 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!149 &1 +NetworkManager: + m_ObjectHideFlags: 0 + m_DebugLevel: 0 + m_Sendrate: 15 + m_AssetToPrefab: {} diff --git a/csharp/examples/unity/ProjectSettings/PackageManagerSettings.asset b/csharp/examples/unity/ProjectSettings/PackageManagerSettings.asset new file mode 100644 index 00000000..6920e3ad --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/PackageManagerSettings.asset @@ -0,0 +1,38 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &1 +MonoBehaviour: + m_ObjectHideFlags: 61 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 13964, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: + m_ScopedRegistriesSettingsExpanded: 1 + oneTimeWarningShown: 0 + m_Registries: + - m_Id: main + m_Name: + m_Url: https://packages.unity.com + m_Scopes: [] + m_IsDefault: 1 + m_UserSelectedRegistryName: + m_UserAddingNewScopedRegistry: 0 + m_RegistryInfoDraft: + m_ErrorMessage: + m_Original: + m_Id: + m_Name: + m_Url: + m_Scopes: [] + m_IsDefault: 0 + m_Modified: 0 + m_Name: + m_Url: + m_Scopes: + - + m_SelectedScopeIndex: 0 diff --git a/csharp/examples/unity/ProjectSettings/Physics2DSettings.asset b/csharp/examples/unity/ProjectSettings/Physics2DSettings.asset new file mode 100644 index 00000000..47880b1c --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/Physics2DSettings.asset @@ -0,0 +1,56 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!19 &1 +Physics2DSettings: + m_ObjectHideFlags: 0 + serializedVersion: 4 + m_Gravity: {x: 0, y: -9.81} + m_DefaultMaterial: {fileID: 0} + m_VelocityIterations: 8 + m_PositionIterations: 3 + m_VelocityThreshold: 1 + m_MaxLinearCorrection: 0.2 + m_MaxAngularCorrection: 8 + m_MaxTranslationSpeed: 100 + m_MaxRotationSpeed: 360 + m_BaumgarteScale: 0.2 + m_BaumgarteTimeOfImpactScale: 0.75 + m_TimeToSleep: 0.5 + m_LinearSleepTolerance: 0.01 + m_AngularSleepTolerance: 2 + m_DefaultContactOffset: 0.01 + m_JobOptions: + serializedVersion: 2 + useMultithreading: 0 + useConsistencySorting: 0 + m_InterpolationPosesPerJob: 100 + m_NewContactsPerJob: 30 + m_CollideContactsPerJob: 100 + m_ClearFlagsPerJob: 200 + m_ClearBodyForcesPerJob: 200 + m_SyncDiscreteFixturesPerJob: 50 + m_SyncContinuousFixturesPerJob: 50 + m_FindNearestContactsPerJob: 100 + m_UpdateTriggerContactsPerJob: 100 + m_IslandSolverCostThreshold: 100 + m_IslandSolverBodyCostScale: 1 + m_IslandSolverContactCostScale: 10 + m_IslandSolverJointCostScale: 10 + m_IslandSolverBodiesPerJob: 50 + m_IslandSolverContactsPerJob: 50 + m_AutoSimulation: 1 + m_QueriesHitTriggers: 1 + m_QueriesStartInColliders: 1 + m_CallbacksOnDisable: 1 + m_ReuseCollisionCallbacks: 1 + m_AutoSyncTransforms: 0 + m_AlwaysShowColliders: 0 + m_ShowColliderSleep: 1 + m_ShowColliderContacts: 0 + m_ShowColliderAABB: 0 + m_ContactArrowScale: 0.2 + m_ColliderAwakeColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.7529412} + m_ColliderAsleepColor: {r: 0.5686275, g: 0.95686275, b: 0.54509807, a: 0.36078432} + m_ColliderContactColor: {r: 1, g: 0, b: 1, a: 0.6862745} + m_ColliderAABBColor: {r: 1, g: 1, b: 0, a: 0.2509804} + m_LayerCollisionMatrix: ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff diff --git a/csharp/examples/unity/ProjectSettings/PresetManager.asset b/csharp/examples/unity/ProjectSettings/PresetManager.asset new file mode 100644 index 00000000..67a94dae --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/PresetManager.asset @@ -0,0 +1,7 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1386491679 &1 +PresetManager: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_DefaultPresets: {} diff --git a/csharp/examples/unity/ProjectSettings/ProjectSettings.asset b/csharp/examples/unity/ProjectSettings/ProjectSettings.asset new file mode 100644 index 00000000..a2c7e05c --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/ProjectSettings.asset @@ -0,0 +1,675 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!129 &1 +PlayerSettings: + m_ObjectHideFlags: 0 + serializedVersion: 20 + productGUID: 1a35671d5af6cd641b60d60e5aeea17f + AndroidProfiler: 0 + AndroidFilterTouchesWhenObscured: 0 + AndroidEnableSustainedPerformanceMode: 0 + defaultScreenOrientation: 4 + targetDevice: 2 + useOnDemandResources: 0 + accelerometerFrequency: 60 + companyName: DefaultCompany + productName: unity + defaultCursor: {fileID: 0} + cursorHotspot: {x: 0, y: 0} + m_SplashScreenBackgroundColor: {r: 0.13725491, g: 0.12156863, b: 0.1254902, a: 1} + m_ShowUnitySplashScreen: 1 + m_ShowUnitySplashLogo: 1 + m_SplashScreenOverlayOpacity: 1 + m_SplashScreenAnimation: 1 + m_SplashScreenLogoStyle: 1 + m_SplashScreenDrawMode: 0 + m_SplashScreenBackgroundAnimationZoom: 1 + m_SplashScreenLogoAnimationZoom: 1 + m_SplashScreenBackgroundLandscapeAspect: 1 + m_SplashScreenBackgroundPortraitAspect: 1 + m_SplashScreenBackgroundLandscapeUvs: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + m_SplashScreenBackgroundPortraitUvs: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + m_SplashScreenLogos: [] + m_VirtualRealitySplashScreen: {fileID: 0} + m_HolographicTrackingLossScreen: {fileID: 0} + defaultScreenWidth: 1024 + defaultScreenHeight: 768 + defaultScreenWidthWeb: 960 + defaultScreenHeightWeb: 600 + m_StereoRenderingPath: 0 + m_ActiveColorSpace: 0 + m_MTRendering: 1 + m_StackTraceTypes: 010000000100000001000000010000000100000001000000 + iosShowActivityIndicatorOnLoading: -1 + androidShowActivityIndicatorOnLoading: -1 + iosUseCustomAppBackgroundBehavior: 0 + iosAllowHTTPDownload: 1 + allowedAutorotateToPortrait: 1 + allowedAutorotateToPortraitUpsideDown: 1 + allowedAutorotateToLandscapeRight: 1 + allowedAutorotateToLandscapeLeft: 1 + useOSAutorotation: 1 + use32BitDisplayBuffer: 1 + preserveFramebufferAlpha: 0 + disableDepthAndStencilBuffers: 0 + androidStartInFullscreen: 1 + androidRenderOutsideSafeArea: 1 + androidUseSwappy: 0 + androidBlitType: 0 + defaultIsNativeResolution: 1 + macRetinaSupport: 1 + runInBackground: 1 + captureSingleScreen: 0 + muteOtherAudioSources: 0 + Prepare IOS For Recording: 0 + Force IOS Speakers When Recording: 0 + deferSystemGesturesMode: 0 + hideHomeButton: 0 + submitAnalytics: 1 + usePlayerLog: 1 + bakeCollisionMeshes: 0 + forceSingleInstance: 0 + useFlipModelSwapchain: 1 + resizableWindow: 0 + useMacAppStoreValidation: 0 + macAppStoreCategory: public.app-category.games + gpuSkinning: 0 + xboxPIXTextureCapture: 0 + xboxEnableAvatar: 0 + xboxEnableKinect: 0 + xboxEnableKinectAutoTracking: 0 + xboxEnableFitness: 0 + visibleInBackground: 1 + allowFullscreenSwitch: 1 + fullscreenMode: 1 + xboxSpeechDB: 0 + xboxEnableHeadOrientation: 0 + xboxEnableGuest: 0 + xboxEnablePIXSampling: 0 + metalFramebufferOnly: 0 + xboxOneResolution: 0 + xboxOneSResolution: 0 + xboxOneXResolution: 3 + xboxOneMonoLoggingLevel: 0 + xboxOneLoggingLevel: 1 + xboxOneDisableEsram: 0 + xboxOneEnableTypeOptimization: 0 + xboxOnePresentImmediateThreshold: 0 + switchQueueCommandMemory: 0 + switchQueueControlMemory: 16384 + switchQueueComputeMemory: 262144 + switchNVNShaderPoolsGranularity: 33554432 + switchNVNDefaultPoolsGranularity: 16777216 + switchNVNOtherPoolsGranularity: 16777216 + switchNVNMaxPublicTextureIDCount: 0 + switchNVNMaxPublicSamplerIDCount: 0 + stadiaPresentMode: 0 + stadiaTargetFramerate: 0 + vulkanNumSwapchainBuffers: 3 + vulkanEnableSetSRGBWrite: 0 + vulkanEnableLateAcquireNextImage: 0 + m_SupportedAspectRatios: + 4:3: 1 + 5:4: 1 + 16:10: 1 + 16:9: 1 + Others: 1 + bundleVersion: 0.1 + preloadedAssets: [] + metroInputSource: 0 + wsaTransparentSwapchain: 0 + m_HolographicPauseOnTrackingLoss: 1 + xboxOneDisableKinectGpuReservation: 1 + xboxOneEnable7thCore: 1 + vrSettings: + cardboard: + depthFormat: 0 + enableTransitionView: 0 + daydream: + depthFormat: 0 + useSustainedPerformanceMode: 0 + enableVideoLayer: 0 + useProtectedVideoMemory: 0 + minimumSupportedHeadTracking: 0 + maximumSupportedHeadTracking: 1 + hololens: + depthFormat: 1 + depthBufferSharingEnabled: 1 + lumin: + depthFormat: 0 + frameTiming: 2 + enableGLCache: 0 + glCacheMaxBlobSize: 524288 + glCacheMaxFileSize: 8388608 + oculus: + sharedDepthBuffer: 1 + dashSupport: 1 + lowOverheadMode: 0 + protectedContext: 0 + v2Signing: 1 + enable360StereoCapture: 0 + isWsaHolographicRemotingEnabled: 0 + enableFrameTimingStats: 0 + useHDRDisplay: 0 + D3DHDRBitDepth: 0 + m_ColorGamuts: 00000000 + targetPixelDensity: 30 + resolutionScalingMode: 0 + androidSupportedAspectRatio: 1 + androidMaxAspectRatio: 2.1 + applicationIdentifier: {} + buildNumber: {} + AndroidBundleVersionCode: 1 + AndroidMinSdkVersion: 19 + AndroidTargetSdkVersion: 0 + AndroidPreferredInstallLocation: 1 + aotOptions: + stripEngineCode: 1 + iPhoneStrippingLevel: 0 + iPhoneScriptCallOptimization: 0 + ForceInternetPermission: 0 + ForceSDCardPermission: 0 + CreateWallpaper: 0 + APKExpansionFiles: 0 + keepLoadedShadersAlive: 0 + StripUnusedMeshComponents: 1 + VertexChannelCompressionMask: 4054 + iPhoneSdkVersion: 988 + iOSTargetOSVersionString: 10.0 + tvOSSdkVersion: 0 + tvOSRequireExtendedGameController: 0 + tvOSTargetOSVersionString: 10.0 + uIPrerenderedIcon: 0 + uIRequiresPersistentWiFi: 0 + uIRequiresFullScreen: 1 + uIStatusBarHidden: 1 + uIExitOnSuspend: 0 + uIStatusBarStyle: 0 + appleTVSplashScreen: {fileID: 0} + appleTVSplashScreen2x: {fileID: 0} + tvOSSmallIconLayers: [] + tvOSSmallIconLayers2x: [] + tvOSLargeIconLayers: [] + tvOSLargeIconLayers2x: [] + tvOSTopShelfImageLayers: [] + tvOSTopShelfImageLayers2x: [] + tvOSTopShelfImageWideLayers: [] + tvOSTopShelfImageWideLayers2x: [] + iOSLaunchScreenType: 0 + iOSLaunchScreenPortrait: {fileID: 0} + iOSLaunchScreenLandscape: {fileID: 0} + iOSLaunchScreenBackgroundColor: + serializedVersion: 2 + rgba: 0 + iOSLaunchScreenFillPct: 100 + iOSLaunchScreenSize: 100 + iOSLaunchScreenCustomXibPath: + iOSLaunchScreeniPadType: 0 + iOSLaunchScreeniPadImage: {fileID: 0} + iOSLaunchScreeniPadBackgroundColor: + serializedVersion: 2 + rgba: 0 + iOSLaunchScreeniPadFillPct: 100 + iOSLaunchScreeniPadSize: 100 + iOSLaunchScreeniPadCustomXibPath: + iOSUseLaunchScreenStoryboard: 0 + iOSLaunchScreenCustomStoryboardPath: + iOSDeviceRequirements: [] + iOSURLSchemes: [] + iOSBackgroundModes: 0 + iOSMetalForceHardShadows: 0 + metalEditorSupport: 1 + metalAPIValidation: 1 + iOSRenderExtraFrameOnPause: 0 + iosCopyPluginsCodeInsteadOfSymlink: 0 + appleDeveloperTeamID: + iOSManualSigningProvisioningProfileID: + tvOSManualSigningProvisioningProfileID: + iOSManualSigningProvisioningProfileType: 0 + tvOSManualSigningProvisioningProfileType: 0 + appleEnableAutomaticSigning: 0 + iOSRequireARKit: 0 + iOSAutomaticallyDetectAndAddCapabilities: 1 + appleEnableProMotion: 0 + clonedFromGUID: 5f34be1353de5cf4398729fda238591b + templatePackageId: com.unity.template.2d@3.3.2 + templateDefaultScene: Assets/Scenes/SampleScene.unity + AndroidTargetArchitectures: 1 + AndroidSplashScreenScale: 0 + androidSplashScreen: {fileID: 0} + AndroidKeystoreName: + AndroidKeyaliasName: + AndroidBuildApkPerCpuArchitecture: 0 + AndroidTVCompatibility: 0 + AndroidIsGame: 1 + AndroidEnableTango: 0 + androidEnableBanner: 1 + androidUseLowAccuracyLocation: 0 + androidUseCustomKeystore: 0 + m_AndroidBanners: + - width: 320 + height: 180 + banner: {fileID: 0} + androidGamepadSupportLevel: 0 + AndroidValidateAppBundleSize: 1 + AndroidAppBundleSizeToValidate: 150 + m_BuildTargetIcons: [] + m_BuildTargetPlatformIcons: [] + m_BuildTargetBatching: [] + m_BuildTargetGraphicsJobs: + - m_BuildTarget: MacStandaloneSupport + m_GraphicsJobs: 0 + - m_BuildTarget: Switch + m_GraphicsJobs: 0 + - m_BuildTarget: MetroSupport + m_GraphicsJobs: 0 + - m_BuildTarget: AppleTVSupport + m_GraphicsJobs: 0 + - m_BuildTarget: BJMSupport + m_GraphicsJobs: 0 + - m_BuildTarget: LinuxStandaloneSupport + m_GraphicsJobs: 0 + - m_BuildTarget: PS4Player + m_GraphicsJobs: 0 + - m_BuildTarget: iOSSupport + m_GraphicsJobs: 0 + - m_BuildTarget: WindowsStandaloneSupport + m_GraphicsJobs: 0 + - m_BuildTarget: XboxOnePlayer + m_GraphicsJobs: 0 + - m_BuildTarget: LuminSupport + m_GraphicsJobs: 0 + - m_BuildTarget: AndroidPlayer + m_GraphicsJobs: 0 + - m_BuildTarget: WebGLSupport + m_GraphicsJobs: 0 + m_BuildTargetGraphicsJobMode: + - m_BuildTarget: PS4Player + m_GraphicsJobMode: 0 + - m_BuildTarget: XboxOnePlayer + m_GraphicsJobMode: 0 + m_BuildTargetGraphicsAPIs: + - m_BuildTarget: AndroidPlayer + m_APIs: 150000000b000000 + m_Automatic: 0 + m_BuildTargetVRSettings: [] + openGLRequireES31: 0 + openGLRequireES31AEP: 0 + openGLRequireES32: 0 + m_TemplateCustomTags: {} + mobileMTRendering: + Android: 1 + iPhone: 1 + tvOS: 1 + m_BuildTargetGroupLightmapEncodingQuality: [] + m_BuildTargetGroupLightmapSettings: [] + playModeTestRunnerEnabled: 0 + runPlayModeTestAsEditModeTest: 0 + actionOnDotNetUnhandledException: 1 + enableInternalProfiler: 0 + logObjCUncaughtExceptions: 1 + enableCrashReportAPI: 0 + cameraUsageDescription: + locationUsageDescription: + microphoneUsageDescription: + switchNetLibKey: + switchSocketMemoryPoolSize: 6144 + switchSocketAllocatorPoolSize: 128 + switchSocketConcurrencyLimit: 14 + switchScreenResolutionBehavior: 2 + switchUseCPUProfiler: 0 + switchApplicationID: 0x01004b9000490000 + switchNSODependencies: + switchTitleNames_0: + switchTitleNames_1: + switchTitleNames_2: + switchTitleNames_3: + switchTitleNames_4: + switchTitleNames_5: + switchTitleNames_6: + switchTitleNames_7: + switchTitleNames_8: + switchTitleNames_9: + switchTitleNames_10: + switchTitleNames_11: + switchTitleNames_12: + switchTitleNames_13: + switchTitleNames_14: + switchTitleNames_15: + switchPublisherNames_0: + switchPublisherNames_1: + switchPublisherNames_2: + switchPublisherNames_3: + switchPublisherNames_4: + switchPublisherNames_5: + switchPublisherNames_6: + switchPublisherNames_7: + switchPublisherNames_8: + switchPublisherNames_9: + switchPublisherNames_10: + switchPublisherNames_11: + switchPublisherNames_12: + switchPublisherNames_13: + switchPublisherNames_14: + switchPublisherNames_15: + switchIcons_0: {fileID: 0} + switchIcons_1: {fileID: 0} + switchIcons_2: {fileID: 0} + switchIcons_3: {fileID: 0} + switchIcons_4: {fileID: 0} + switchIcons_5: {fileID: 0} + switchIcons_6: {fileID: 0} + switchIcons_7: {fileID: 0} + switchIcons_8: {fileID: 0} + switchIcons_9: {fileID: 0} + switchIcons_10: {fileID: 0} + switchIcons_11: {fileID: 0} + switchIcons_12: {fileID: 0} + switchIcons_13: {fileID: 0} + switchIcons_14: {fileID: 0} + switchIcons_15: {fileID: 0} + switchSmallIcons_0: {fileID: 0} + switchSmallIcons_1: {fileID: 0} + switchSmallIcons_2: {fileID: 0} + switchSmallIcons_3: {fileID: 0} + switchSmallIcons_4: {fileID: 0} + switchSmallIcons_5: {fileID: 0} + switchSmallIcons_6: {fileID: 0} + switchSmallIcons_7: {fileID: 0} + switchSmallIcons_8: {fileID: 0} + switchSmallIcons_9: {fileID: 0} + switchSmallIcons_10: {fileID: 0} + switchSmallIcons_11: {fileID: 0} + switchSmallIcons_12: {fileID: 0} + switchSmallIcons_13: {fileID: 0} + switchSmallIcons_14: {fileID: 0} + switchSmallIcons_15: {fileID: 0} + switchManualHTML: + switchAccessibleURLs: + switchLegalInformation: + switchMainThreadStackSize: 1048576 + switchPresenceGroupId: + switchLogoHandling: 0 + switchReleaseVersion: 0 + switchDisplayVersion: 1.0.0 + switchStartupUserAccount: 0 + switchTouchScreenUsage: 0 + switchSupportedLanguagesMask: 0 + switchLogoType: 0 + switchApplicationErrorCodeCategory: + switchUserAccountSaveDataSize: 0 + switchUserAccountSaveDataJournalSize: 0 + switchApplicationAttribute: 0 + switchCardSpecSize: -1 + switchCardSpecClock: -1 + switchRatingsMask: 0 + switchRatingsInt_0: 0 + switchRatingsInt_1: 0 + switchRatingsInt_2: 0 + switchRatingsInt_3: 0 + switchRatingsInt_4: 0 + switchRatingsInt_5: 0 + switchRatingsInt_6: 0 + switchRatingsInt_7: 0 + switchRatingsInt_8: 0 + switchRatingsInt_9: 0 + switchRatingsInt_10: 0 + switchRatingsInt_11: 0 + switchRatingsInt_12: 0 + switchLocalCommunicationIds_0: + switchLocalCommunicationIds_1: + switchLocalCommunicationIds_2: + switchLocalCommunicationIds_3: + switchLocalCommunicationIds_4: + switchLocalCommunicationIds_5: + switchLocalCommunicationIds_6: + switchLocalCommunicationIds_7: + switchParentalControl: 0 + switchAllowsScreenshot: 1 + switchAllowsVideoCapturing: 1 + switchAllowsRuntimeAddOnContentInstall: 0 + switchDataLossConfirmation: 0 + switchUserAccountLockEnabled: 0 + switchSystemResourceMemory: 16777216 + switchSupportedNpadStyles: 22 + switchNativeFsCacheSize: 32 + switchIsHoldTypeHorizontal: 0 + switchSupportedNpadCount: 8 + switchSocketConfigEnabled: 0 + switchTcpInitialSendBufferSize: 32 + switchTcpInitialReceiveBufferSize: 64 + switchTcpAutoSendBufferSizeMax: 256 + switchTcpAutoReceiveBufferSizeMax: 256 + switchUdpSendBufferSize: 9 + switchUdpReceiveBufferSize: 42 + switchSocketBufferEfficiency: 4 + switchSocketInitializeEnabled: 1 + switchNetworkInterfaceManagerInitializeEnabled: 1 + switchPlayerConnectionEnabled: 1 + switchUseMicroSleepForYield: 1 + switchMicroSleepForYieldTime: 25 + ps4NPAgeRating: 12 + ps4NPTitleSecret: + ps4NPTrophyPackPath: + ps4ParentalLevel: 11 + ps4ContentID: ED1633-NPXX51362_00-0000000000000000 + ps4Category: 0 + ps4MasterVersion: 01.00 + ps4AppVersion: 01.00 + ps4AppType: 0 + ps4ParamSfxPath: + ps4VideoOutPixelFormat: 0 + ps4VideoOutInitialWidth: 1920 + ps4VideoOutBaseModeInitialWidth: 1920 + ps4VideoOutReprojectionRate: 60 + ps4PronunciationXMLPath: + ps4PronunciationSIGPath: + ps4BackgroundImagePath: + ps4StartupImagePath: + ps4StartupImagesFolder: + ps4IconImagesFolder: + ps4SaveDataImagePath: + ps4SdkOverride: + ps4BGMPath: + ps4ShareFilePath: + ps4ShareOverlayImagePath: + ps4PrivacyGuardImagePath: + ps4ExtraSceSysFile: + ps4NPtitleDatPath: + ps4RemotePlayKeyAssignment: -1 + ps4RemotePlayKeyMappingDir: + ps4PlayTogetherPlayerCount: 0 + ps4EnterButtonAssignment: 1 + ps4ApplicationParam1: 0 + ps4ApplicationParam2: 0 + ps4ApplicationParam3: 0 + ps4ApplicationParam4: 0 + ps4DownloadDataSize: 0 + ps4GarlicHeapSize: 2048 + ps4ProGarlicHeapSize: 2560 + playerPrefsMaxSize: 32768 + ps4Passcode: frAQBc8Wsa1xVPfvJcrgRYwTiizs2trQ + ps4pnSessions: 1 + ps4pnPresence: 1 + ps4pnFriends: 1 + ps4pnGameCustomData: 1 + playerPrefsSupport: 0 + enableApplicationExit: 0 + resetTempFolder: 1 + restrictedAudioUsageRights: 0 + ps4UseResolutionFallback: 0 + ps4ReprojectionSupport: 0 + ps4UseAudio3dBackend: 0 + ps4UseLowGarlicFragmentationMode: 1 + ps4SocialScreenEnabled: 0 + ps4ScriptOptimizationLevel: 0 + ps4Audio3dVirtualSpeakerCount: 14 + ps4attribCpuUsage: 0 + ps4PatchPkgPath: + ps4PatchLatestPkgPath: + ps4PatchChangeinfoPath: + ps4PatchDayOne: 0 + ps4attribUserManagement: 0 + ps4attribMoveSupport: 0 + ps4attrib3DSupport: 0 + ps4attribShareSupport: 0 + ps4attribExclusiveVR: 0 + ps4disableAutoHideSplash: 0 + ps4videoRecordingFeaturesUsed: 0 + ps4contentSearchFeaturesUsed: 0 + ps4CompatibilityPS5: 0 + ps4AllowPS5Detection: 0 + ps4GPU800MHz: 1 + ps4attribEyeToEyeDistanceSettingVR: 0 + ps4IncludedModules: [] + ps4attribVROutputEnabled: 0 + ps5ParamFilePath: + ps5VideoOutPixelFormat: 0 + ps5VideoOutInitialWidth: 1920 + ps5VideoOutOutputMode: 1 + ps5BackgroundImagePath: + ps5StartupImagePath: + ps5Pic2Path: + ps5StartupImagesFolder: + ps5IconImagesFolder: + ps5SaveDataImagePath: + ps5SdkOverride: + ps5BGMPath: + ps5ShareOverlayImagePath: + ps5NPConfigZipPath: + ps5Passcode: frAQBc8Wsa1xVPfvJcrgRYwTiizs2trQ + ps5UseResolutionFallback: 0 + ps5UseAudio3dBackend: 0 + ps5ScriptOptimizationLevel: 2 + ps5Audio3dVirtualSpeakerCount: 14 + ps5UpdateReferencePackage: + ps5disableAutoHideSplash: 0 + ps5OperatingSystemCanDisableSplashScreen: 0 + ps5IncludedModules: [] + ps5SharedBinaryContentLabels: [] + ps5SharedBinarySystemFolders: [] + monoEnv: + splashScreenBackgroundSourceLandscape: {fileID: 0} + splashScreenBackgroundSourcePortrait: {fileID: 0} + blurSplashScreenBackground: 1 + spritePackerPolicy: + webGLMemorySize: 16 + webGLExceptionSupport: 1 + webGLNameFilesAsHashes: 0 + webGLDataCaching: 1 + webGLDebugSymbols: 0 + webGLEmscriptenArgs: + webGLModulesDirectory: + webGLTemplate: APPLICATION:Default + webGLAnalyzeBuildSize: 0 + webGLUseEmbeddedResources: 0 + webGLCompressionFormat: 1 + webGLLinkerTarget: 1 + webGLThreadsSupport: 0 + webGLWasmStreaming: 0 + scriptingDefineSymbols: {} + platformArchitecture: {} + scriptingBackend: {} + il2cppCompilerConfiguration: {} + managedStrippingLevel: {} + incrementalIl2cppBuild: {} + suppressCommonWarnings: 1 + allowUnsafeCode: 0 + additionalIl2CppArgs: + scriptingRuntimeVersion: 1 + gcIncremental: 0 + assemblyVersionValidation: 1 + gcWBarrierValidation: 0 + apiCompatibilityLevelPerPlatform: {} + m_RenderingPath: 1 + m_MobileRenderingPath: 1 + metroPackageName: Template_2D + metroPackageVersion: + metroCertificatePath: + metroCertificatePassword: + metroCertificateSubject: + metroCertificateIssuer: + metroCertificateNotAfter: 0000000000000000 + metroApplicationDescription: Template_2D + wsaImages: {} + metroTileShortName: + metroTileShowName: 0 + metroMediumTileShowName: 0 + metroLargeTileShowName: 0 + metroWideTileShowName: 0 + metroSupportStreamingInstall: 0 + metroLastRequiredScene: 0 + metroDefaultTileSize: 1 + metroTileForegroundText: 2 + metroTileBackgroundColor: {r: 0.13333334, g: 0.17254902, b: 0.21568628, a: 0} + metroSplashScreenBackgroundColor: {r: 0.12941177, g: 0.17254902, b: 0.21568628, + a: 1} + metroSplashScreenUseBackgroundColor: 0 + platformCapabilities: {} + metroTargetDeviceFamilies: {} + metroFTAName: + metroFTAFileTypes: [] + metroProtocolName: + XboxOneProductId: + XboxOneUpdateKey: + XboxOneSandboxId: + XboxOneContentId: + XboxOneTitleId: + XboxOneSCId: + XboxOneGameOsOverridePath: + XboxOnePackagingOverridePath: + XboxOneAppManifestOverridePath: + XboxOneVersion: 1.0.0.0 + XboxOnePackageEncryption: 0 + XboxOnePackageUpdateGranularity: 2 + XboxOneDescription: + XboxOneLanguage: + - enus + XboxOneCapability: [] + XboxOneGameRating: {} + XboxOneIsContentPackage: 0 + XboxOneEnhancedXboxCompatibilityMode: 0 + XboxOneEnableGPUVariability: 1 + XboxOneSockets: {} + XboxOneSplashScreen: {fileID: 0} + XboxOneAllowedProductIds: [] + XboxOnePersistentLocalStorageSize: 0 + XboxOneXTitleMemory: 8 + XboxOneOverrideIdentityName: + XboxOneOverrideIdentityPublisher: + vrEditorSettings: + daydream: + daydreamIconForeground: {fileID: 0} + daydreamIconBackground: {fileID: 0} + cloudServicesEnabled: + UNet: 1 + luminIcon: + m_Name: + m_ModelFolderPath: + m_PortalFolderPath: + luminCert: + m_CertPath: + m_SignPackage: 1 + luminIsChannelApp: 0 + luminVersion: + m_VersionCode: 1 + m_VersionName: + apiCompatibilityLevel: 6 + cloudProjectId: + framebufferDepthMemorylessMode: 0 + projectName: + organizationId: + cloudEnabled: 0 + enableNativePlatformBackendsForNewInputSystem: 0 + disableOldInputManagerSupport: 0 + legacyClampBlendShapeWeights: 0 diff --git a/csharp/examples/unity/ProjectSettings/ProjectVersion.txt b/csharp/examples/unity/ProjectSettings/ProjectVersion.txt new file mode 100644 index 00000000..ecaedcdb --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/ProjectVersion.txt @@ -0,0 +1,2 @@ +m_EditorVersion: 2019.4.29f1 +m_EditorVersionWithRevision: 2019.4.29f1 (0eeae20b1d82) diff --git a/csharp/examples/unity/ProjectSettings/QualitySettings.asset b/csharp/examples/unity/ProjectSettings/QualitySettings.asset new file mode 100644 index 00000000..84c16101 --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/QualitySettings.asset @@ -0,0 +1,192 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!47 &1 +QualitySettings: + m_ObjectHideFlags: 0 + serializedVersion: 5 + m_CurrentQuality: 3 + m_QualitySettings: + - serializedVersion: 2 + name: Very Low + pixelLightCount: 0 + shadows: 0 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 15 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 1 + textureQuality: 1 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 0 + lodBias: 0.3 + maximumLODLevel: 0 + particleRaycastBudget: 4 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Low + pixelLightCount: 0 + shadows: 0 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 20 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 0 + lodBias: 0.4 + maximumLODLevel: 0 + particleRaycastBudget: 16 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Medium + pixelLightCount: 1 + shadows: 0 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 1 + shadowDistance: 20 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 0 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 0 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 1 + lodBias: 0.7 + maximumLODLevel: 0 + particleRaycastBudget: 64 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: High + pixelLightCount: 2 + shadows: 0 + shadowResolution: 1 + shadowProjection: 1 + shadowCascades: 2 + shadowDistance: 40 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 2 + textureQuality: 0 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 1 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 1 + lodBias: 1 + maximumLODLevel: 0 + particleRaycastBudget: 256 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Very High + pixelLightCount: 3 + shadows: 0 + shadowResolution: 2 + shadowProjection: 1 + shadowCascades: 2 + shadowDistance: 70 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 4 + textureQuality: 0 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 1 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 1 + lodBias: 1.5 + maximumLODLevel: 0 + particleRaycastBudget: 1024 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + - serializedVersion: 2 + name: Ultra + pixelLightCount: 4 + shadows: 0 + shadowResolution: 0 + shadowProjection: 1 + shadowCascades: 4 + shadowDistance: 150 + shadowNearPlaneOffset: 3 + shadowCascade2Split: 0.33333334 + shadowCascade4Split: {x: 0.06666667, y: 0.2, z: 0.46666667} + shadowmaskMode: 1 + blendWeights: 4 + textureQuality: 0 + anisotropicTextures: 0 + antiAliasing: 0 + softParticles: 0 + softVegetation: 1 + realtimeReflectionProbes: 0 + billboardsFaceCameraPosition: 0 + vSyncCount: 1 + lodBias: 2 + maximumLODLevel: 0 + particleRaycastBudget: 4096 + asyncUploadTimeSlice: 2 + asyncUploadBufferSize: 16 + resolutionScalingFixedDPIFactor: 1 + excludedTargetPlatforms: [] + m_PerPlatformDefaultQuality: + Android: 2 + Nintendo 3DS: 5 + Nintendo Switch: 5 + PS4: 5 + PSM: 5 + PSP2: 2 + Stadia: 5 + Standalone: 5 + Tizen: 2 + WebGL: 3 + WiiU: 5 + Windows Store Apps: 5 + XboxOne: 5 + iPhone: 2 + tvOS: 2 diff --git a/csharp/examples/unity/ProjectSettings/TagManager.asset b/csharp/examples/unity/ProjectSettings/TagManager.asset new file mode 100644 index 00000000..1c92a784 --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/TagManager.asset @@ -0,0 +1,43 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!78 &1 +TagManager: + serializedVersion: 2 + tags: [] + layers: + - Default + - TransparentFX + - Ignore Raycast + - + - Water + - UI + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + m_SortingLayers: + - name: Default + uniqueID: 0 + locked: 0 diff --git a/csharp/examples/unity/ProjectSettings/TimeManager.asset b/csharp/examples/unity/ProjectSettings/TimeManager.asset new file mode 100644 index 00000000..06bcc6d2 --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/TimeManager.asset @@ -0,0 +1,9 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!5 &1 +TimeManager: + m_ObjectHideFlags: 0 + Fixed Timestep: 0.02 + Maximum Allowed Timestep: 0.1 + m_TimeScale: 1 + Maximum Particle Timestep: 0.03 diff --git a/csharp/examples/unity/ProjectSettings/UnityConnectSettings.asset b/csharp/examples/unity/ProjectSettings/UnityConnectSettings.asset new file mode 100644 index 00000000..fa0b1465 --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/UnityConnectSettings.asset @@ -0,0 +1,34 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!310 &1 +UnityConnectSettings: + m_ObjectHideFlags: 0 + serializedVersion: 1 + m_Enabled: 0 + m_TestMode: 0 + m_EventOldUrl: https://api.uca.cloud.unity3d.com/v1/events + m_EventUrl: https://cdp.cloud.unity3d.com/v1/events + m_ConfigUrl: https://config.uca.cloud.unity3d.com + m_TestInitMode: 0 + CrashReportingSettings: + m_EventUrl: https://perf-events.cloud.unity3d.com + m_Enabled: 0 + m_LogBufferSize: 10 + m_CaptureEditorExceptions: 1 + UnityPurchasingSettings: + m_Enabled: 0 + m_TestMode: 0 + UnityAnalyticsSettings: + m_Enabled: 0 + m_TestMode: 0 + m_InitializeOnStartup: 1 + UnityAdsSettings: + m_Enabled: 0 + m_InitializeOnStartup: 1 + m_TestMode: 0 + m_IosGameId: + m_AndroidGameId: + m_GameIds: {} + m_GameId: + PerformanceReportingSettings: + m_Enabled: 0 diff --git a/csharp/examples/unity/ProjectSettings/VFXManager.asset b/csharp/examples/unity/ProjectSettings/VFXManager.asset new file mode 100644 index 00000000..3a95c98b --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/VFXManager.asset @@ -0,0 +1,12 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!937362698 &1 +VFXManager: + m_ObjectHideFlags: 0 + m_IndirectShader: {fileID: 0} + m_CopyBufferShader: {fileID: 0} + m_SortShader: {fileID: 0} + m_StripUpdateShader: {fileID: 0} + m_RenderPipeSettingsPath: + m_FixedTimeStep: 0.016666668 + m_MaxDeltaTime: 0.05 diff --git a/csharp/examples/unity/ProjectSettings/XRSettings.asset b/csharp/examples/unity/ProjectSettings/XRSettings.asset new file mode 100644 index 00000000..482590c1 --- /dev/null +++ b/csharp/examples/unity/ProjectSettings/XRSettings.asset @@ -0,0 +1,10 @@ +{ + "m_SettingKeys": [ + "VR Device Disabled", + "VR Device User Alert" + ], + "m_SettingValues": [ + "False", + "False" + ] +} \ No newline at end of file diff --git a/csharp/netfx.props b/csharp/netfx.props new file mode 100644 index 00000000..91ab5efd --- /dev/null +++ b/csharp/netfx.props @@ -0,0 +1,28 @@ + + + + + + + true + + + /Library/Frameworks/Mono.framework/Versions/Current/lib/mono + /usr/lib/mono + /usr/local/lib/mono + + + $(BaseFrameworkPathOverrideForMono)/4.5-api + $(BaseFrameworkPathOverrideForMono)/4.5.1-api + $(BaseFrameworkPathOverrideForMono)/4.5.2-api + $(BaseFrameworkPathOverrideForMono)/4.6-api + $(BaseFrameworkPathOverrideForMono)/4.6.1-api + $(BaseFrameworkPathOverrideForMono)/4.6.2-api + $(BaseFrameworkPathOverrideForMono)/4.7-api + $(BaseFrameworkPathOverrideForMono)/4.7.1-api + true + + + $(FrameworkPathOverride)/Facades;$(AssemblySearchPaths) + + diff --git a/csharp/pitaya-sharp.sln b/csharp/pitaya-sharp.sln new file mode 100644 index 00000000..39293d3a --- /dev/null +++ b/csharp/pitaya-sharp.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NPitaya", "NPitaya\NPitaya.csproj", "{465A09E9-B3EB-48CC-97F9-71A361A170CF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "exampleapp", "exampleapp\exampleapp.csproj", "{A50BECF7-8EBD-4451-B390-9B8F33636247}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExampleEFCore", "ExampleEFCore\ExampleEFCore.csproj", "{A677E03C-B5B5-4D0B-9E9B-5CAB6D0591DC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NPitaya.Tests", "NPitaya.Tests\NPitaya.Tests.csproj", "{1ADE34A2-E893-4DDA-901C-905D7FC7B394}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {465A09E9-B3EB-48CC-97F9-71A361A170CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {465A09E9-B3EB-48CC-97F9-71A361A170CF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {465A09E9-B3EB-48CC-97F9-71A361A170CF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {465A09E9-B3EB-48CC-97F9-71A361A170CF}.Release|Any CPU.Build.0 = Release|Any CPU + {A50BECF7-8EBD-4451-B390-9B8F33636247}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A50BECF7-8EBD-4451-B390-9B8F33636247}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A50BECF7-8EBD-4451-B390-9B8F33636247}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A50BECF7-8EBD-4451-B390-9B8F33636247}.Release|Any CPU.Build.0 = Release|Any CPU + {A677E03C-B5B5-4D0B-9E9B-5CAB6D0591DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A677E03C-B5B5-4D0B-9E9B-5CAB6D0591DC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A677E03C-B5B5-4D0B-9E9B-5CAB6D0591DC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A677E03C-B5B5-4D0B-9E9B-5CAB6D0591DC}.Release|Any CPU.Build.0 = Release|Any CPU + {1ADE34A2-E893-4DDA-901C-905D7FC7B394}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1ADE34A2-E893-4DDA-901C-905D7FC7B394}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1ADE34A2-E893-4DDA-901C-905D7FC7B394}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1ADE34A2-E893-4DDA-901C-905D7FC7B394}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/e2e/e2e_test.go b/e2e/e2e_test.go index 7c91db3a..2b004790 100644 --- a/e2e/e2e_test.go +++ b/e2e/e2e_test.go @@ -23,6 +23,8 @@ package e2e import ( "flag" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/client" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" "os" "os/exec" "testing" @@ -31,9 +33,7 @@ import ( "github.com/google/uuid" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/client" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/helpers" + "github.com/topfreegames/pitaya/v3/pkg/helpers" ) var update = flag.Bool("update", false, "update server binary") diff --git a/examples/demo/chat/main.go b/examples/demo/chat/main.go index a8b194a1..580cdb79 100644 --- a/examples/demo/chat/main.go +++ b/examples/demo/chat/main.go @@ -3,6 +3,10 @@ package main import ( "context" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/groups" "log" "net/http" "strconv" @@ -10,20 +14,16 @@ import ( "strings" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/groups" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/timer" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/timer" ) type ( // Room represents a component that contains a bundle of room related handler // like Join/Message Room struct { - component.Base + component2.Base timer *timer.Timer app pitaya.Pitaya } @@ -121,8 +121,8 @@ func main() { // rewrite component and handler name room := NewRoom(app) app.Register(room, - component.WithName("room"), - component.WithNameFunc(strings.ToLower), + component2.WithName("room"), + component2.WithNameFunc(strings.ToLower), ) log.SetFlags(log.LstdFlags | log.Llongfile) diff --git a/examples/demo/cluster/main.go b/examples/demo/cluster/main.go index 422609d9..52f32cef 100644 --- a/examples/demo/cluster/main.go +++ b/examples/demo/cluster/main.go @@ -4,17 +4,17 @@ import ( "context" "flag" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/groups" "strings" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/examples/demo/cluster/services" - "github.com/topfreegames/pitaya/v2/groups" - "github.com/topfreegames/pitaya/v2/route" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/examples/demo/cluster/services" + "github.com/topfreegames/pitaya/v3/pkg/route" ) var app pitaya.Pitaya diff --git a/examples/demo/cluster/services/connector.go b/examples/demo/cluster/services/connector.go index c4c265f1..c9a271f5 100644 --- a/examples/demo/cluster/services/connector.go +++ b/examples/demo/cluster/services/connector.go @@ -4,11 +4,11 @@ import ( "context" "encoding/json" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/component" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/examples/demo/protos" - pitayaprotos "github.com/topfreegames/pitaya/v2/protos" + "github.com/topfreegames/pitaya/v3/examples/demo/protos" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + pitayaprotos "github.com/topfreegames/pitaya/v3/pkg/protos" ) // ConnectorRemote is a remote that will receive rpc's diff --git a/examples/demo/cluster/services/room.go b/examples/demo/cluster/services/room.go index 896d52c2..592c9047 100644 --- a/examples/demo/cluster/services/room.go +++ b/examples/demo/cluster/services/room.go @@ -3,12 +3,12 @@ package services import ( "context" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/component" "time" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/examples/demo/protos" - "github.com/topfreegames/pitaya/v2/timer" + "github.com/topfreegames/pitaya/v3/examples/demo/protos" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/pkg/timer" ) type ( diff --git a/examples/demo/cluster_grpc/main.go b/examples/demo/cluster_grpc/main.go index a1e59f57..9ec907b5 100644 --- a/examples/demo/cluster_grpc/main.go +++ b/examples/demo/cluster_grpc/main.go @@ -4,20 +4,20 @@ import ( "context" "flag" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + cluster2 "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" + "github.com/topfreegames/pitaya/v3/pkg/groups" "strconv" "strings" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/examples/demo/cluster_grpc/services" - "github.com/topfreegames/pitaya/v2/groups" - "github.com/topfreegames/pitaya/v2/modules" - "github.com/topfreegames/pitaya/v2/route" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/examples/demo/cluster_grpc/services" + "github.com/topfreegames/pitaya/v3/pkg/modules" + "github.com/topfreegames/pitaya/v3/pkg/route" ) var app pitaya.Pitaya @@ -49,8 +49,8 @@ func configureFrontend(port int) { ctx context.Context, route *route.Route, payload []byte, - servers map[string]*cluster.Server, - ) (*cluster.Server, error) { + servers map[string]*cluster2.Server, + ) (*cluster2.Server, error) { // will return the first server for k := range servers { return servers[k], nil @@ -107,7 +107,7 @@ func createApp(port int, isFrontend bool, svType string, meta map[string]string, grpcServerConfig := config.NewDefaultGRPCServerConfig() grpcServerConfig.Port = rpcServerPort - gs, err := cluster.NewGRPCServer(*grpcServerConfig, builder.Server, builder.MetricsReporters) + gs, err := cluster2.NewGRPCServer(*grpcServerConfig, builder.Server, builder.MetricsReporters) if err != nil { panic(err) } @@ -116,12 +116,12 @@ func createApp(port int, isFrontend bool, svType string, meta map[string]string, bs := modules.NewETCDBindingStorage(builder.Server, builder.SessionPool, *config.NewDefaultETCDBindingConfig()) - gc, err := cluster.NewGRPCClient( + gc, err := cluster2.NewGRPCClient( *config.NewDefaultGRPCClientConfig(), builder.Server, builder.MetricsReporters, bs, - cluster.NewInfoRetriever(*config.NewDefaultInfoRetrieverConfig()), + cluster2.NewInfoRetriever(*config.NewDefaultInfoRetrieverConfig()), ) if err != nil { panic(err) diff --git a/examples/demo/cluster_grpc/services/connector.go b/examples/demo/cluster_grpc/services/connector.go index 0c48b030..cb13ca43 100644 --- a/examples/demo/cluster_grpc/services/connector.go +++ b/examples/demo/cluster_grpc/services/connector.go @@ -3,10 +3,10 @@ package services import ( "context" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/component" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/examples/demo/protos" + "github.com/topfreegames/pitaya/v3/examples/demo/protos" + pitaya "github.com/topfreegames/pitaya/v3/pkg" ) // ConnectorRemote is a remote that will receive rpc's diff --git a/examples/demo/cluster_grpc/services/room.go b/examples/demo/cluster_grpc/services/room.go index cc628077..c6467c34 100644 --- a/examples/demo/cluster_grpc/services/room.go +++ b/examples/demo/cluster_grpc/services/room.go @@ -4,13 +4,13 @@ import ( "context" "encoding/gob" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/component" "strconv" "time" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/examples/demo/protos" - "github.com/topfreegames/pitaya/v2/timer" + "github.com/topfreegames/pitaya/v3/examples/demo/protos" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/pkg/timer" ) type ( diff --git a/examples/demo/custom_metrics/main.go b/examples/demo/custom_metrics/main.go index 3b4013d8..8ae8bd29 100644 --- a/examples/demo/custom_metrics/main.go +++ b/examples/demo/custom_metrics/main.go @@ -3,14 +3,14 @@ package main import ( "flag" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/config" "strings" "github.com/spf13/viper" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/examples/demo/custom_metrics/services" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/examples/demo/custom_metrics/services" ) var app pitaya.Pitaya diff --git a/examples/demo/custom_metrics/services/room.go b/examples/demo/custom_metrics/services/room.go index e7d58836..cc466353 100644 --- a/examples/demo/custom_metrics/services/room.go +++ b/examples/demo/custom_metrics/services/room.go @@ -2,10 +2,10 @@ package services import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/component" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/examples/demo/custom_metrics/messages" + "github.com/topfreegames/pitaya/v3/examples/demo/custom_metrics/messages" + pitaya "github.com/topfreegames/pitaya/v3/pkg" ) // Room server diff --git a/examples/demo/pipeline/main.go b/examples/demo/pipeline/main.go index f86b4311..b82848a6 100644 --- a/examples/demo/pipeline/main.go +++ b/examples/demo/pipeline/main.go @@ -4,16 +4,16 @@ import ( "context" "flag" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/config" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" + pitaya "github.com/topfreegames/pitaya/v3/pkg" ) // MetagameServer ... type MetagameServer struct { - component.Base + component2.Base } // NewMetagameMock ... @@ -110,7 +110,7 @@ func main() { defer app.Shutdown() app.Register(metagameServer, - component.WithName("metagameHandler"), + component2.WithName("metagameHandler"), ) app.Start() diff --git a/examples/demo/rate_limiting/main.go b/examples/demo/rate_limiting/main.go index b4b112bb..b2805fc4 100644 --- a/examples/demo/rate_limiting/main.go +++ b/examples/demo/rate_limiting/main.go @@ -3,34 +3,34 @@ package main import ( "flag" "fmt" + acceptor2 "github.com/topfreegames/pitaya/v3/pkg/acceptor" + acceptorwrapper2 "github.com/topfreegames/pitaya/v3/pkg/acceptorwrapper" + "github.com/topfreegames/pitaya/v3/pkg/component" + config2 "github.com/topfreegames/pitaya/v3/pkg/config" "strings" "time" "github.com/spf13/viper" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/acceptorwrapper" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/examples/demo/rate_limiting/services" - "github.com/topfreegames/pitaya/v2/metrics" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/examples/demo/rate_limiting/services" + "github.com/topfreegames/pitaya/v3/pkg/metrics" ) -func createAcceptor(port int, reporters []metrics.Reporter) acceptor.Acceptor { +func createAcceptor(port int, reporters []metrics.Reporter) acceptor2.Acceptor { // 5 requests in 1 minute. Doesn't make sense, just to test // rate limiting vConfig := viper.New() vConfig.Set("pitaya.conn.ratelimiting.limit", 5) vConfig.Set("pitaya.conn.ratelimiting.interval", time.Minute) - pConfig := config.NewConfig(vConfig) + pConfig := config2.NewConfig(vConfig) - rateLimitConfig := config.NewRateLimitingConfig(pConfig) + rateLimitConfig := config2.NewRateLimitingConfig(pConfig) - tcp := acceptor.NewTCPAcceptor(fmt.Sprintf(":%d", port)) - return acceptorwrapper.WithWrappers( + tcp := acceptor2.NewTCPAcceptor(fmt.Sprintf(":%d", port)) + return acceptorwrapper2.WithWrappers( tcp, - acceptorwrapper.NewRateLimitingWrapper(reporters, *rateLimitConfig)) + acceptorwrapper2.NewRateLimitingWrapper(reporters, *rateLimitConfig)) } var app pitaya.Pitaya @@ -41,7 +41,7 @@ func main() { flag.Parse() - config := config.NewDefaultBuilderConfig() + config := config2.NewDefaultBuilderConfig() builder := pitaya.NewDefaultBuilder(true, svType, pitaya.Cluster, map[string]string{}, *config) builder.AddAcceptor(createAcceptor(*port, builder.MetricsReporters)) diff --git a/examples/demo/rate_limiting/services/room.go b/examples/demo/rate_limiting/services/room.go index 20b23076..683b48ce 100644 --- a/examples/demo/rate_limiting/services/room.go +++ b/examples/demo/rate_limiting/services/room.go @@ -2,8 +2,7 @@ package services import ( "context" - - "github.com/topfreegames/pitaya/v2/component" + "github.com/topfreegames/pitaya/v3/pkg/component" ) // Room represents a component that contains a bundle of room related handler diff --git a/examples/demo/worker/main.go b/examples/demo/worker/main.go index 00809434..1e0d4229 100644 --- a/examples/demo/worker/main.go +++ b/examples/demo/worker/main.go @@ -3,15 +3,15 @@ package main import ( "flag" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/config" "strings" "github.com/spf13/viper" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/examples/demo/worker/services" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/examples/demo/worker/services" ) var app pitaya.Pitaya diff --git a/examples/demo/worker/services/metagame.go b/examples/demo/worker/services/metagame.go index 413f0b9d..df22bb0a 100644 --- a/examples/demo/worker/services/metagame.go +++ b/examples/demo/worker/services/metagame.go @@ -2,10 +2,10 @@ package services import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/component" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/examples/demo/worker/protos" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/examples/demo/worker/protos" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) // Metagame server diff --git a/examples/demo/worker/services/room.go b/examples/demo/worker/services/room.go index 227619b8..dba451e6 100644 --- a/examples/demo/worker/services/room.go +++ b/examples/demo/worker/services/room.go @@ -2,11 +2,11 @@ package services import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/component" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/examples/demo/worker/protos" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/examples/demo/worker/protos" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) // Room server diff --git a/examples/demo/worker/services/worker.go b/examples/demo/worker/services/worker.go index 01bca358..3a6c2566 100644 --- a/examples/demo/worker/services/worker.go +++ b/examples/demo/worker/services/worker.go @@ -2,11 +2,11 @@ package services import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/component" "github.com/golang/protobuf/proto" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/examples/demo/worker/protos" + "github.com/topfreegames/pitaya/v3/examples/demo/worker/protos" + pitaya "github.com/topfreegames/pitaya/v3/pkg" ) // Worker server diff --git a/examples/testing/main.go b/examples/testing/main.go index bd55ecfb..23204410 100644 --- a/examples/testing/main.go +++ b/examples/testing/main.go @@ -25,37 +25,37 @@ import ( "errors" "flag" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + cluster2 "github.com/topfreegames/pitaya/v3/pkg/cluster" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" + config2 "github.com/topfreegames/pitaya/v3/pkg/config" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + "github.com/topfreegames/pitaya/v3/pkg/groups" "strings" "github.com/google/uuid" "github.com/sirupsen/logrus" "github.com/spf13/viper" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/examples/testing/protos" - "github.com/topfreegames/pitaya/v2/groups" - logruswrapper "github.com/topfreegames/pitaya/v2/logger/logrus" - "github.com/topfreegames/pitaya/v2/modules" - "github.com/topfreegames/pitaya/v2/protos/test" - "github.com/topfreegames/pitaya/v2/serialize/json" - "github.com/topfreegames/pitaya/v2/serialize/protobuf" - "github.com/topfreegames/pitaya/v2/session" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/examples/testing/protos" + logruswrapper "github.com/topfreegames/pitaya/v3/pkg/logger/logrus" + "github.com/topfreegames/pitaya/v3/pkg/modules" + "github.com/topfreegames/pitaya/v3/pkg/protos/test" + "github.com/topfreegames/pitaya/v3/pkg/serialize/json" + "github.com/topfreegames/pitaya/v3/pkg/serialize/protobuf" + "github.com/topfreegames/pitaya/v3/pkg/session" ) // TestSvc service for e2e tests type TestSvc struct { - component.Base + component2.Base app pitaya.Pitaya sessionPool session.SessionPool } // TestRemoteSvc remote service for e2e tests type TestRemoteSvc struct { - component.Base + component2.Base } // TestRPCRequest for e2e tests @@ -111,7 +111,7 @@ func (t *TestSvc) Init() { func (t *TestSvc) TestRequestKickUser(ctx context.Context, userID []byte) (*test.TestResponse, error) { s := t.sessionPool.GetSessionByUID(string(userID)) if s == nil { - return nil, pitaya.Error(constants.ErrSessionNotFound, "PIT-404") + return nil, pitaya.Error(constants2.ErrSessionNotFound, "PIT-404") } err := s.Kick(ctx) if err != nil { @@ -127,7 +127,7 @@ func (t *TestSvc) TestRequestKickUser(ctx context.Context, userID []byte) (*test func (t *TestSvc) TestRequestKickMe(ctx context.Context) (*test.TestResponse, error) { s := t.app.GetSessionFromCtx(ctx) if s == nil { - return nil, pitaya.Error(constants.ErrSessionNotFound, "PIT-404") + return nil, pitaya.Error(constants2.ErrSessionNotFound, "PIT-404") } err := s.Kick(ctx) if err != nil { @@ -272,8 +272,8 @@ func main() { pitaya.SetLogger(logruswrapper.NewWithFieldLogger(l)) app, bs, sessionPool := createApp(*serializer, *port, *grpc, *isFrontend, *svType, pitaya.Cluster, map[string]string{ - constants.GRPCHostKey: "127.0.0.1", - constants.GRPCPortKey: fmt.Sprintf("%d", *grpcPort), + constants2.GRPCHostKey: "127.0.0.1", + constants2.GRPCPortKey: fmt.Sprintf("%d", *grpcPort), }, cfg) if *grpc { @@ -285,21 +285,21 @@ func main() { app: app, sessionPool: sessionPool, }, - component.WithName("testsvc"), - component.WithNameFunc(strings.ToLower), + component2.WithName("testsvc"), + component2.WithNameFunc(strings.ToLower), ) app.RegisterRemote( &TestRemoteSvc{}, - component.WithName("testremotesvc"), - component.WithNameFunc(strings.ToLower), + component2.WithName("testremotesvc"), + component2.WithNameFunc(strings.ToLower), ) app.Start() } func createApp(serializer string, port int, grpc bool, isFrontend bool, svType string, serverMode pitaya.ServerMode, metadata map[string]string, cfg ...*viper.Viper) (pitaya.Pitaya, *modules.ETCDBindingStorage, session.SessionPool) { - conf := config.NewConfig(cfg...) + conf := config2.NewConfig(cfg...) builder := pitaya.NewBuilderWithConfigs(isFrontend, svType, serverMode, metadata, conf) if isFrontend { @@ -307,7 +307,7 @@ func createApp(serializer string, port int, grpc bool, isFrontend bool, svType s builder.AddAcceptor(tcp) } - builder.Groups = groups.NewMemoryGroupService(*config.NewDefaultMemoryGroupConfig()) + builder.Groups = groups.NewMemoryGroupService(*config2.NewDefaultMemoryGroupConfig()) if serializer == "json" { builder.Serializer = json.NewSerializer() @@ -319,19 +319,19 @@ func createApp(serializer string, port int, grpc bool, isFrontend bool, svType s var bs *modules.ETCDBindingStorage if grpc { - gs, err := cluster.NewGRPCServer(*config.NewGRPCServerConfig(conf), builder.Server, builder.MetricsReporters) + gs, err := cluster2.NewGRPCServer(*config2.NewGRPCServerConfig(conf), builder.Server, builder.MetricsReporters) if err != nil { panic(err) } - bs = modules.NewETCDBindingStorage(builder.Server, builder.SessionPool, *config.NewETCDBindingConfig(conf)) + bs = modules.NewETCDBindingStorage(builder.Server, builder.SessionPool, *config2.NewETCDBindingConfig(conf)) - gc, err := cluster.NewGRPCClient( - *config.NewGRPCClientConfig(conf), + gc, err := cluster2.NewGRPCClient( + *config2.NewGRPCClientConfig(conf), builder.Server, builder.MetricsReporters, bs, - cluster.NewInfoRetriever(*config.NewInfoRetrieverConfig(conf)), + cluster2.NewInfoRetriever(*config2.NewInfoRetrieverConfig(conf)), ) if err != nil { panic(err) diff --git a/go.mod b/go.mod index 4e1bb2b9..31a48922 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/topfreegames/pitaya/v2 +module github.com/topfreegames/pitaya/v3 go 1.17 @@ -10,12 +10,14 @@ require ( github.com/google/uuid v1.1.4 github.com/gorilla/websocket v1.5.0 github.com/jhump/protoreflect v1.8.2 + github.com/mitchellh/go-homedir v1.0.0 github.com/nats-io/nats-server/v2 v2.8.4 github.com/nats-io/nats.go v1.15.0 github.com/nats-io/nuid v1.0.1 github.com/opentracing/opentracing-go v1.2.0 github.com/prometheus/client_golang v1.11.0 github.com/sirupsen/logrus v1.8.1 + github.com/spf13/cobra v1.2.1 github.com/spf13/viper v1.8.1 github.com/stretchr/testify v1.7.0 github.com/topfreegames/go-workers v1.0.1 @@ -26,11 +28,14 @@ require ( golang.org/x/net v0.0.0-20220105145211-5b0dc2dfae98 google.golang.org/grpc v1.41.0 google.golang.org/protobuf v1.27.1 + gopkg.in/abiosoft/ishell.v2 v2.0.0 ) require ( - github.com/HdrHistogram/hdrhistogram-go v1.1.0 // indirect + github.com/HdrHistogram/hdrhistogram-go v1.1.1 // indirect github.com/Microsoft/go-winio v0.4.16 // indirect + github.com/abiosoft/ishell v2.0.0+incompatible // indirect + github.com/abiosoft/readline v0.0.0-20180607040430-155bce2042db // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bitly/go-simplejson v0.5.0 // indirect github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirect @@ -41,6 +46,8 @@ require ( github.com/customerio/gospec v0.0.0-20130710230057-a5cc0e48aa39 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/dustin/go-humanize v1.0.0 // indirect + github.com/fatih/color v1.7.0 // indirect + github.com/flynn-archive/go-shlex v0.0.0-20150515145356-3f9db97f8568 // indirect github.com/fsnotify/fsnotify v1.4.9 // indirect github.com/garyburd/redigo v1.6.0 // indirect github.com/go-playground/locales v0.13.0 // indirect @@ -54,10 +61,13 @@ require ( github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 // indirect github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect + github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/jonboulle/clockwork v0.2.2 // indirect github.com/klauspost/compress v1.14.4 // indirect github.com/leodido/go-urn v1.2.1 // indirect github.com/magiconair/properties v1.8.5 // indirect + github.com/mattn/go-colorable v0.0.9 // indirect + github.com/mattn/go-isatty v0.0.3 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect github.com/minio/highwayhash v1.0.2 // indirect github.com/mitchellh/mapstructure v1.4.1 // indirect diff --git a/go.sum b/go.sum index e58ab3d0..f28233e2 100644 --- a/go.sum +++ b/go.sum @@ -43,11 +43,15 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03 github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/DataDog/datadog-go v4.5.0+incompatible h1:MyyuIz5LVAI3Im+0F/tfo64ETyH4sNVynZ29yOiHm50= github.com/DataDog/datadog-go v4.5.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= -github.com/HdrHistogram/hdrhistogram-go v1.1.0 h1:6dpdDPTRoo78HxAJ6T1HfMiKSnqhgRRqzCuPshRkQ7I= -github.com/HdrHistogram/hdrhistogram-go v1.1.0/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo= +github.com/HdrHistogram/hdrhistogram-go v1.1.1 h1:cJXY5VLMHgejurPjZH6Fo9rIwRGLefBGdiaENZALqrg= +github.com/HdrHistogram/hdrhistogram-go v1.1.1/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo= github.com/Microsoft/go-winio v0.4.16 h1:FtSW/jqD+l4ba5iPBj9CODVtgfYAD8w2wS923g/cFDk= github.com/Microsoft/go-winio v0.4.16/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/abiosoft/ishell v2.0.0+incompatible h1:zpwIuEHc37EzrsIYah3cpevrIc8Oma7oZPxr03tlmmw= +github.com/abiosoft/ishell v2.0.0+incompatible/go.mod h1:HQR9AqF2R3P4XXpMpI0NAzgHf/aS6+zVXRj14cVk9qg= +github.com/abiosoft/readline v0.0.0-20180607040430-155bce2042db h1:CjPUSXOiYptLbTdr1RceuZgSFDQ7U15ITERUGrUORx8= +github.com/abiosoft/readline v0.0.0-20180607040430-155bce2042db/go.mod h1:rB3B4rKii8V21ydCbIzH5hZiCQE7f5E9SzUb/ZZx530= github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= @@ -78,8 +82,10 @@ github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/chzyer/logex v1.1.10 h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= @@ -116,7 +122,10 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.m github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/flynn-archive/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BMXYYRWTLOJKlh+lOBt6nUQgXAfB7oVIQt5cNreqSLI= +github.com/flynn-archive/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:rZfgFAXFS/z/lEd6LJmf9HVZ1LkgYiHx5pHhV5DR16M= github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= @@ -258,6 +267,7 @@ github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2p github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jhump/protoreflect v1.8.2 h1:k2xE7wcUomeqwY0LDCYA16y4WWfyTcMx5mKhk0d4ua0= github.com/jhump/protoreflect v1.8.2/go.mod h1:7GcYQDdMU/O/BBrl/cX6PNHpXh6cenjd8pneu5yW7Tg= @@ -294,7 +304,9 @@ github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= +github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= +github.com/mattn/go-isatty v0.0.3 h1:ns/ykhmWi7G9O+8a448SecJU3nSMBXJfqQkl0upE1jI= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= @@ -303,6 +315,7 @@ github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3N github.com/minio/highwayhash v1.0.2 h1:Aak5U0nElisjDCfPSG79Tgzkn2gl66NxOMspRrKnA/g= github.com/minio/highwayhash v1.0.2/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= +github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= @@ -387,6 +400,7 @@ github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v1.2.1 h1:+KmjbUw1hriSNMF55oPrkZcb27aECyrj8V2ytv7kWDw= github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -852,6 +866,8 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0 google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +gopkg.in/abiosoft/ishell.v2 v2.0.0 h1:/J5yh3nWYSSGFjALcitTI9CLE0Tu27vBYHX0srotqOc= +gopkg.in/abiosoft/ishell.v2 v2.0.0/go.mod h1:sFp+cGtH6o4s1FtpVPTMcHq2yue+c4DGOVohJCPUzwY= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/logger/logrus/logrus.go b/logger/logrus/logrus.go index 3d92a827..3a929ca2 100644 --- a/logger/logrus/logrus.go +++ b/logger/logrus/logrus.go @@ -2,7 +2,7 @@ package logrus import ( "github.com/sirupsen/logrus" - "github.com/topfreegames/pitaya/v2/logger/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/logger/interfaces" ) type logrusImpl struct { diff --git a/main.go b/main.go new file mode 100644 index 00000000..83cd117f --- /dev/null +++ b/main.go @@ -0,0 +1,22 @@ +/* +Copyright © 2021 Wildlife Studios + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package main + +import "github.com/topfreegames/pitaya/v3/cmd" + +func main() { + cmd.Execute() +} diff --git a/networkentity/mocks/networkentity.go b/networkentity/mocks/networkentity.go index 5405436a..a3e84694 100644 --- a/networkentity/mocks/networkentity.go +++ b/networkentity/mocks/networkentity.go @@ -1,5 +1,5 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/topfreegames/pitaya/v2/networkentity (interfaces: NetworkEntity) +// Source: github.com/topfreegames/pitaya/v3/pkg/networkentity (interfaces: NetworkEntity) // Package mocks is a generated GoMock package. package mocks @@ -7,7 +7,7 @@ package mocks import ( context "context" gomock "github.com/golang/mock/gomock" - protos "github.com/topfreegames/pitaya/v2/protos" + protos "github.com/topfreegames/pitaya/v3/pkg/protos" net "net" reflect "reflect" ) diff --git a/networkentity/networkentity.go b/networkentity/networkentity.go index eed4cadf..84aced9c 100644 --- a/networkentity/networkentity.go +++ b/networkentity/networkentity.go @@ -4,7 +4,7 @@ import ( "context" "net" - "github.com/topfreegames/pitaya/v2/protos" + "github.com/topfreegames/pitaya/v3/pkg/protos" ) // NetworkEntity represent low-level network instance diff --git a/pitaya-protos b/pitaya-protos index fa9c1679..15ac298d 160000 --- a/pitaya-protos +++ b/pitaya-protos @@ -1 +1 @@ -Subproject commit fa9c167930df2b0a6ded6ad67a75ee9c803f622b +Subproject commit 15ac298d3be2de0932eb68df1ef5d52e6133e7d0 diff --git a/acceptor/acceptor.go b/pkg/acceptor/acceptor.go similarity index 100% rename from acceptor/acceptor.go rename to pkg/acceptor/acceptor.go diff --git a/acceptor/fixtures/server.crt b/pkg/acceptor/fixtures/server.crt similarity index 100% rename from acceptor/fixtures/server.crt rename to pkg/acceptor/fixtures/server.crt diff --git a/acceptor/fixtures/server.key b/pkg/acceptor/fixtures/server.key similarity index 100% rename from acceptor/fixtures/server.key rename to pkg/acceptor/fixtures/server.key diff --git a/acceptor/tcp_acceptor.go b/pkg/acceptor/tcp_acceptor.go similarity index 93% rename from acceptor/tcp_acceptor.go rename to pkg/acceptor/tcp_acceptor.go index 10f2f870..9dd87cbf 100644 --- a/acceptor/tcp_acceptor.go +++ b/pkg/acceptor/tcp_acceptor.go @@ -22,13 +22,13 @@ package acceptor import ( "crypto/tls" + codec2 "github.com/topfreegames/pitaya/v3/pkg/conn/codec" + "github.com/topfreegames/pitaya/v3/pkg/constants" "io" "io/ioutil" "net" - "github.com/topfreegames/pitaya/v2/conn/codec" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) // TCPAcceptor struct @@ -47,7 +47,7 @@ type tcpPlayerConn struct { // GetNextMessage reads the next message available in the stream func (t *tcpPlayerConn) GetNextMessage() (b []byte, err error) { - header, err := ioutil.ReadAll(io.LimitReader(t.Conn, codec.HeadLength)) + header, err := ioutil.ReadAll(io.LimitReader(t.Conn, codec2.HeadLength)) if err != nil { return nil, err } @@ -55,7 +55,7 @@ func (t *tcpPlayerConn) GetNextMessage() (b []byte, err error) { if len(header) == 0 { return nil, constants.ErrConnectionClosed } - msgSize, _, err := codec.ParseHeader(header) + msgSize, _, err := codec2.ParseHeader(header) if err != nil { return nil, err } diff --git a/acceptor/tcp_acceptor_test.go b/pkg/acceptor/tcp_acceptor_test.go similarity index 98% rename from acceptor/tcp_acceptor_test.go rename to pkg/acceptor/tcp_acceptor_test.go index ff3d524f..eca32d43 100644 --- a/acceptor/tcp_acceptor_test.go +++ b/pkg/acceptor/tcp_acceptor_test.go @@ -21,14 +21,14 @@ package acceptor import ( + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" + "github.com/topfreegames/pitaya/v3/pkg/constants" "net" "testing" "time" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/conn/packet" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/helpers" + "github.com/topfreegames/pitaya/v3/pkg/helpers" ) var tcpAcceptorTables = []struct { diff --git a/acceptor/ws_acceptor.go b/pkg/acceptor/ws_acceptor.go similarity index 90% rename from acceptor/ws_acceptor.go rename to pkg/acceptor/ws_acceptor.go index 90f78b38..7cd566eb 100644 --- a/acceptor/ws_acceptor.go +++ b/pkg/acceptor/ws_acceptor.go @@ -22,16 +22,16 @@ package acceptor import ( "crypto/tls" + codec2 "github.com/topfreegames/pitaya/v3/pkg/conn/codec" + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" "io" "net" "net/http" "time" "github.com/gorilla/websocket" - "github.com/topfreegames/pitaya/v2/conn/codec" - "github.com/topfreegames/pitaya/v2/conn/packet" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) // WSAcceptor struct @@ -48,7 +48,7 @@ func NewWSAcceptor(addr string, certs ...string) *WSAcceptor { keyFile := "" certFile := "" if len(certs) != 2 && len(certs) != 0 { - panic(constants.ErrInvalidCertificates) + panic(constants2.ErrInvalidCertificates) } else if len(certs) == 2 { certFile = certs[0] keyFile = certs[1] @@ -108,8 +108,8 @@ func (w *WSAcceptor) ListenAndServe() { } var upgrader = websocket.Upgrader{ - ReadBufferSize: constants.IOBufferBytesSize, - WriteBufferSize: constants.IOBufferBytesSize, + ReadBufferSize: constants2.IOBufferBytesSize, + WriteBufferSize: constants2.IOBufferBytesSize, CheckOrigin: func(r *http.Request) bool { return true }, @@ -127,8 +127,8 @@ func (w *WSAcceptor) ListenAndServe() { // ListenAndServeTLS listens and serve in the specified addr using tls func (w *WSAcceptor) ListenAndServeTLS(cert, key string) { var upgrader = websocket.Upgrader{ - ReadBufferSize: constants.IOBufferBytesSize, - WriteBufferSize: constants.IOBufferBytesSize, + ReadBufferSize: constants2.IOBufferBytesSize, + WriteBufferSize: constants2.IOBufferBytesSize, } crt, err := tls.LoadX509KeyPair(cert, key) @@ -183,19 +183,19 @@ func (c *WSConn) GetNextMessage() (b []byte, err error) { if err != nil { return nil, err } - if len(msgBytes) < codec.HeadLength { + if len(msgBytes) < codec2.HeadLength { return nil, packet.ErrInvalidPomeloHeader } - header := msgBytes[:codec.HeadLength] - msgSize, _, err := codec.ParseHeader(header) + header := msgBytes[:codec2.HeadLength] + msgSize, _, err := codec2.ParseHeader(header) if err != nil { return nil, err } - dataLen := len(msgBytes[codec.HeadLength:]) + dataLen := len(msgBytes[codec2.HeadLength:]) if dataLen < msgSize { - return nil, constants.ErrReceivedMsgSmallerThanExpected + return nil, constants2.ErrReceivedMsgSmallerThanExpected } else if dataLen > msgSize { - return nil, constants.ErrReceivedMsgBiggerThanExpected + return nil, constants2.ErrReceivedMsgBiggerThanExpected } return msgBytes, err } diff --git a/acceptor/ws_acceptor_test.go b/pkg/acceptor/ws_acceptor_test.go similarity index 98% rename from acceptor/ws_acceptor_test.go rename to pkg/acceptor/ws_acceptor_test.go index 2e668141..4beb7ebb 100644 --- a/acceptor/ws_acceptor_test.go +++ b/pkg/acceptor/ws_acceptor_test.go @@ -3,14 +3,14 @@ package acceptor import ( "crypto/tls" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" + "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "time" "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/conn/packet" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/helpers" + "github.com/topfreegames/pitaya/v3/pkg/helpers" ) var wsAcceptorTables = []struct { diff --git a/acceptorwrapper/base.go b/pkg/acceptorwrapper/base.go similarity index 97% rename from acceptorwrapper/base.go rename to pkg/acceptorwrapper/base.go index e9a48b81..dc866405 100644 --- a/acceptorwrapper/base.go +++ b/pkg/acceptorwrapper/base.go @@ -21,7 +21,7 @@ package acceptorwrapper import ( - "github.com/topfreegames/pitaya/v2/acceptor" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" ) // BaseWrapper implements Wrapper by saving the acceptor as an attribute. diff --git a/acceptorwrapper/base_test.go b/pkg/acceptorwrapper/base_test.go similarity index 95% rename from acceptorwrapper/base_test.go rename to pkg/acceptorwrapper/base_test.go index 3feeea49..8e1f27ef 100644 --- a/acceptorwrapper/base_test.go +++ b/pkg/acceptorwrapper/base_test.go @@ -21,13 +21,12 @@ package acceptorwrapper import ( + "github.com/topfreegames/pitaya/v3/pkg/acceptor" "testing" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/mocks" + "github.com/topfreegames/pitaya/v3/pkg/mocks" ) func TestListenAndServe(t *testing.T) { diff --git a/acceptorwrapper/rate_limiter.go b/pkg/acceptorwrapper/rate_limiter.go similarity index 94% rename from acceptorwrapper/rate_limiter.go rename to pkg/acceptorwrapper/rate_limiter.go index 217ef7ae..d5fdcbf2 100644 --- a/acceptorwrapper/rate_limiter.go +++ b/pkg/acceptorwrapper/rate_limiter.go @@ -22,12 +22,12 @@ package acceptorwrapper import ( "container/list" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + "github.com/topfreegames/pitaya/v3/pkg/constants" "time" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/metrics" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/metrics" ) // RateLimiter wraps net.Conn by applying rate limiting and return empty diff --git a/acceptorwrapper/rate_limiter_test.go b/pkg/acceptorwrapper/rate_limiter_test.go similarity index 97% rename from acceptorwrapper/rate_limiter_test.go rename to pkg/acceptorwrapper/rate_limiter_test.go index a59f09d2..871c859c 100644 --- a/acceptorwrapper/rate_limiter_test.go +++ b/pkg/acceptorwrapper/rate_limiter_test.go @@ -27,8 +27,8 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/mocks" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/mocks" ) func TestRateLimiterGetNextMessage(t *testing.T) { diff --git a/acceptorwrapper/rate_limiting_wrapper.go b/pkg/acceptorwrapper/rate_limiting_wrapper.go similarity index 92% rename from acceptorwrapper/rate_limiting_wrapper.go rename to pkg/acceptorwrapper/rate_limiting_wrapper.go index 3c00b257..cbefe69a 100644 --- a/acceptorwrapper/rate_limiting_wrapper.go +++ b/pkg/acceptorwrapper/rate_limiting_wrapper.go @@ -21,9 +21,9 @@ package acceptorwrapper import ( - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/metrics" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + "github.com/topfreegames/pitaya/v3/pkg/config" ) // RateLimitingWrapper rate limits for each connection diff --git a/acceptorwrapper/rate_limiting_wrapper_test.go b/pkg/acceptorwrapper/rate_limiting_wrapper_test.go similarity index 94% rename from acceptorwrapper/rate_limiting_wrapper_test.go rename to pkg/acceptorwrapper/rate_limiting_wrapper_test.go index 610edc64..88c5263f 100644 --- a/acceptorwrapper/rate_limiting_wrapper_test.go +++ b/pkg/acceptorwrapper/rate_limiting_wrapper_test.go @@ -21,12 +21,12 @@ package acceptorwrapper import ( + "github.com/topfreegames/pitaya/v3/pkg/config" "testing" "time" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/metrics" + "github.com/topfreegames/pitaya/v3/pkg/metrics" ) func TestNewRateLimitingWrapper(t *testing.T) { diff --git a/acceptorwrapper/wrapper.go b/pkg/acceptorwrapper/wrapper.go similarity index 97% rename from acceptorwrapper/wrapper.go rename to pkg/acceptorwrapper/wrapper.go index 54faa99b..8ec1aa46 100644 --- a/acceptorwrapper/wrapper.go +++ b/pkg/acceptorwrapper/wrapper.go @@ -21,7 +21,7 @@ package acceptorwrapper import ( - "github.com/topfreegames/pitaya/v2/acceptor" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" ) // Wrapper has a method that receives an acceptor and the struct diff --git a/agent/agent.go b/pkg/agent/agent.go similarity index 84% rename from agent/agent.go rename to pkg/agent/agent.go index a6a89585..6544f0a5 100644 --- a/agent/agent.go +++ b/pkg/agent/agent.go @@ -25,25 +25,25 @@ import ( gojson "encoding/json" e "errors" "fmt" + codec2 "github.com/topfreegames/pitaya/v3/pkg/conn/codec" + message2 "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + "github.com/topfreegames/pitaya/v3/pkg/errors" "net" "strings" "sync" "sync/atomic" "time" - "github.com/topfreegames/pitaya/v2/conn/codec" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/conn/packet" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/serialize" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/tracing" - "github.com/topfreegames/pitaya/v2/util" - "github.com/topfreegames/pitaya/v2/util/compression" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/serialize" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/tracing" + "github.com/topfreegames/pitaya/v3/pkg/util" + "github.com/topfreegames/pitaya/v3/pkg/util/compression" opentracing "github.com/opentracing/opentracing-go" ) @@ -68,12 +68,12 @@ type ( chStopHeartbeat chan struct{} // stop heartbeats chStopWrite chan struct{} // stop writing messages closeMutex sync.Mutex - conn net.Conn // low-level conn fd - decoder codec.PacketDecoder // binary decoder - encoder codec.PacketEncoder // binary encoder + conn net.Conn // low-level conn fd + decoder codec2.PacketDecoder // binary decoder + encoder codec2.PacketEncoder // binary encoder heartbeatTimeout time.Duration lastAt int64 // last heartbeat unix time stamp - messageEncoder message.Encoder + messageEncoder message2.Encoder messagesBufferSize int // size of the pending messages buffer metricsReporters []metrics.Reporter serializer serialize.Serializer // message serializer @@ -82,11 +82,11 @@ type ( pendingMessage struct { ctx context.Context - typ message.Type // message type - route string // message route (push) - mid uint // response message id (response) - payload interface{} // payload - err bool // if its an error message + typ message2.Type // message type + route string // message route (push) + mid uint // response message id (response) + payload interface{} // payload + err bool // if its an error message } pendingWrite struct { @@ -121,11 +121,11 @@ type ( agentFactoryImpl struct { sessionPool session.SessionPool - appDieChan chan bool // app die channel - decoder codec.PacketDecoder // binary decoder - encoder codec.PacketEncoder // binary encoder + appDieChan chan bool // app die channel + decoder codec2.PacketDecoder // binary decoder + encoder codec2.PacketEncoder // binary encoder heartbeatTimeout time.Duration - messageEncoder message.Encoder + messageEncoder message2.Encoder messagesBufferSize int // size of the pending messages buffer metricsReporters []metrics.Reporter serializer serialize.Serializer // message serializer @@ -135,11 +135,11 @@ type ( // NewAgentFactory ctor func NewAgentFactory( appDieChan chan bool, - decoder codec.PacketDecoder, - encoder codec.PacketEncoder, + decoder codec2.PacketDecoder, + encoder codec2.PacketEncoder, serializer serialize.Serializer, heartbeatTimeout time.Duration, - messageEncoder message.Encoder, + messageEncoder message2.Encoder, messagesBufferSize int, sessionPool session.SessionPool, metricsReporters []metrics.Reporter, @@ -165,13 +165,13 @@ func (f *agentFactoryImpl) CreateAgent(conn net.Conn) Agent { // NewAgent create new agent instance func newAgent( conn net.Conn, - packetDecoder codec.PacketDecoder, - packetEncoder codec.PacketEncoder, + packetDecoder codec2.PacketDecoder, + packetEncoder codec2.PacketEncoder, serializer serialize.Serializer, heartbeatTime time.Duration, messagesBufferSize int, dieChan chan bool, - messageEncoder message.Encoder, + messageEncoder message2.Encoder, metricsReporters []metrics.Reporter, sessionPool session.SessionPool, ) Agent { @@ -195,7 +195,7 @@ func newAgent( heartbeatTimeout: heartbeatTime, lastAt: time.Now().Unix(), serializer: serializer, - state: constants.StatusStart, + state: constants2.StatusStart, messageEncoder: messageEncoder, metricsReporters: metricsReporters, sessionPool: sessionPool, @@ -208,7 +208,7 @@ func newAgent( return a } -func (a *agentImpl) getMessageFromPendingMessage(pm pendingMessage) (*message.Message, error) { +func (a *agentImpl) getMessageFromPendingMessage(pm pendingMessage) (*message2.Message, error) { payload, err := util.SerializeOrRaw(a.serializer, pm.payload) if err != nil { payload, err = util.GetErrorPayload(a.serializer, err) @@ -218,7 +218,7 @@ func (a *agentImpl) getMessageFromPendingMessage(pm pendingMessage) (*message.Me } // construct message and encode - m := &message.Message{ + m := &message2.Message{ Type: pm.typ, Data: payload, Route: pm.route, @@ -229,7 +229,7 @@ func (a *agentImpl) getMessageFromPendingMessage(pm pendingMessage) (*message.Me return m, nil } -func (a *agentImpl) packetEncodeMessage(m *message.Message) ([]byte, error) { +func (a *agentImpl) packetEncodeMessage(m *message2.Message) ([]byte, error) { em, err := a.messageEncoder.Encode(m) if err != nil { return nil, err @@ -246,7 +246,7 @@ func (a *agentImpl) packetEncodeMessage(m *message.Message) ([]byte, error) { func (a *agentImpl) send(pendingMsg pendingMessage) (err error) { defer func() { if e := recover(); e != nil { - err = errors.NewError(constants.ErrBrokenPipe, errors.ErrClientClosedRequest) + err = errors.NewError(constants2.ErrBrokenPipe, errors.ErrClientClosedRequest) } }() a.reportChannelSize() @@ -286,8 +286,8 @@ func (a *agentImpl) GetSession() session.Session { // Push implementation for NetworkEntity interface func (a *agentImpl) Push(route string, v interface{}) error { - if a.GetStatus() == constants.StatusClosed { - return errors.NewError(constants.ErrBrokenPipe, errors.ErrClientClosedRequest) + if a.GetStatus() == constants2.StatusClosed { + return errors.NewError(constants2.ErrBrokenPipe, errors.ErrClientClosedRequest) } switch d := v.(type) { @@ -298,7 +298,7 @@ func (a *agentImpl) Push(route string, v interface{}) error { logger.Log.Debugf("Type=Push, ID=%d, UID=%s, Route=%s, Data=%+v", a.Session.ID(), a.Session.UID(), route, v) } - return a.send(pendingMessage{typ: message.Push, route: route, payload: v}) + return a.send(pendingMessage{typ: message2.Push, route: route, payload: v}) } // ResponseMID implementation for NetworkEntity interface @@ -308,12 +308,12 @@ func (a *agentImpl) ResponseMID(ctx context.Context, mid uint, v interface{}, is if len(isError) > 0 { err = isError[0] } - if a.GetStatus() == constants.StatusClosed { - return errors.NewError(constants.ErrBrokenPipe, errors.ErrClientClosedRequest) + if a.GetStatus() == constants2.StatusClosed { + return errors.NewError(constants2.ErrBrokenPipe, errors.ErrClientClosedRequest) } if mid <= 0 { - return constants.ErrSessionOnNotify + return constants2.ErrSessionOnNotify } switch d := v.(type) { @@ -325,7 +325,7 @@ func (a *agentImpl) ResponseMID(ctx context.Context, mid uint, v interface{}, is a.Session.ID(), a.Session.UID(), mid, v) } - return a.send(pendingMessage{ctx: ctx, typ: message.Response, mid: mid, payload: v, err: err}) + return a.send(pendingMessage{ctx: ctx, typ: message2.Response, mid: mid, payload: v, err: err}) } // Close closes the agent, cleans inner state and closes low-level connection. @@ -333,10 +333,10 @@ func (a *agentImpl) ResponseMID(ctx context.Context, mid uint, v interface{}, is func (a *agentImpl) Close() error { a.closeMutex.Lock() defer a.closeMutex.Unlock() - if a.GetStatus() == constants.StatusClosed { - return constants.ErrCloseClosedSession + if a.GetStatus() == constants2.StatusClosed { + return constants2.ErrCloseClosedSession } - a.SetStatus(constants.StatusClosed) + a.SetStatus(constants2.StatusClosed) logger.Log.Debugf("Session closed, ID=%d, UID=%s, IP=%s", a.Session.ID(), a.Session.UID(), a.conn.RemoteAddr()) @@ -413,11 +413,11 @@ func (a *agentImpl) Handle() { // check if there is a colon on the string. // So checking if there are more than one colon here is safe. func (a *agentImpl) IPVersion() string { - version := constants.IPv4 + version := constants2.IPv4 ipPort := a.RemoteAddr().String() if strings.Count(ipPort, ":") > 1 { - version = constants.IPv6 + version = constants2.IPv6 } return version @@ -534,12 +534,12 @@ func (a *agentImpl) AnswerWithError(ctx context.Context, mid uint, err error) { } } -func hbdEncode(heartbeatTimeout time.Duration, packetEncoder codec.PacketEncoder, dataCompression bool, serializerName string) { +func hbdEncode(heartbeatTimeout time.Duration, packetEncoder codec2.PacketEncoder, dataCompression bool, serializerName string) { hData := map[string]interface{}{ "code": 200, "sys": map[string]interface{}{ "heartbeat": heartbeatTimeout.Seconds(), - "dict": message.GetDictionary(), + "dict": message2.GetDictionary(), "serializer": serializerName, }, } diff --git a/agent/agent_remote.go b/pkg/agent/agent_remote.go similarity index 76% rename from agent/agent_remote.go rename to pkg/agent/agent_remote.go index 4e387eda..42f81466 100644 --- a/agent/agent_remote.go +++ b/pkg/agent/agent_remote.go @@ -22,46 +22,46 @@ package agent import ( "context" + cluster2 "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/conn/codec" + message2 "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" "net" "reflect" "github.com/golang/protobuf/proto" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/conn/codec" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/conn/packet" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/serialize" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/util" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/serialize" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/util" ) // Remote corresponding to another server type Remote struct { Session session.Session // session chDie chan struct{} // wait for close - messageEncoder message.Encoder - encoder codec.PacketEncoder // binary encoder - frontendID string // the frontend that sent the request - reply string // nats reply topic - rpcClient cluster.RPCClient // rpc client - serializer serialize.Serializer // message serializer - serviceDiscovery cluster.ServiceDiscovery // service discovery + messageEncoder message2.Encoder + encoder codec.PacketEncoder // binary encoder + frontendID string // the frontend that sent the request + reply string // nats reply topic + rpcClient cluster2.RPCClient // rpc client + serializer serialize.Serializer // message serializer + serviceDiscovery cluster2.ServiceDiscovery // service discovery } // NewRemote create new Remote instance func NewRemote( sess *protos.Session, reply string, - rpcClient cluster.RPCClient, + rpcClient cluster2.RPCClient, encoder codec.PacketEncoder, serializer serialize.Serializer, - serviceDiscovery cluster.ServiceDiscovery, + serviceDiscovery cluster2.ServiceDiscovery, frontendID string, - messageEncoder message.Encoder, + messageEncoder message2.Encoder, sessionPool session.SessionPool, ) (*Remote, error) { a := &Remote{ @@ -90,7 +90,7 @@ func NewRemote( // Kick kicks the user func (a *Remote) Kick(ctx context.Context) error { if a.Session.UID() == "" { - return constants.ErrNoUIDBind + return constants2.ErrNoUIDBind } b, err := proto.Marshal(&protos.KickMsg{ UserId: a.Session.UID(), @@ -98,15 +98,15 @@ func (a *Remote) Kick(ctx context.Context) error { if err != nil { return err } - _, err = a.SendRequest(ctx, a.frontendID, constants.KickRoute, b) + _, err = a.SendRequest(ctx, a.frontendID, constants2.KickRoute, b) return err } // Push pushes the message to the user func (a *Remote) Push(route string, v interface{}) error { - if (reflect.TypeOf(a.rpcClient) == reflect.TypeOf(&cluster.NatsRPCClient{}) && + if (reflect.TypeOf(a.rpcClient) == reflect.TypeOf(&cluster2.NatsRPCClient{}) && a.Session.UID() == "") { - return constants.ErrNoUIDBind + return constants2.ErrNoUIDBind } switch d := v.(type) { case []byte: @@ -122,7 +122,7 @@ func (a *Remote) Push(route string, v interface{}) error { return err } return a.sendPush( - pendingMessage{typ: message.Push, route: route, payload: v}, + pendingMessage{typ: message2.Push, route: route, payload: v}, a.Session.UID(), sv, ) } @@ -135,7 +135,7 @@ func (a *Remote) ResponseMID(ctx context.Context, mid uint, v interface{}, isErr } if mid <= 0 { - return constants.ErrSessionOnNotify + return constants2.ErrSessionOnNotify } switch d := v.(type) { @@ -147,7 +147,7 @@ func (a *Remote) ResponseMID(ctx context.Context, mid uint, v interface{}, isErr a.Session.ID(), mid, v) } - return a.send(pendingMessage{ctx: ctx, typ: message.Response, mid: mid, payload: v, err: err}, a.reply) + return a.send(pendingMessage{ctx: ctx, typ: message2.Response, mid: mid, payload: v, err: err}, a.reply) } // Close closes the remote @@ -163,7 +163,7 @@ func (a *Remote) serialize(m pendingMessage) ([]byte, error) { } // construct message and encode - msg := &message.Message{ + msg := &message2.Message{ Type: m.typ, Data: payload, Route: m.route, @@ -200,7 +200,7 @@ func (a *Remote) send(m pendingMessage, to string) (err error) { return a.rpcClient.Send(to, bt) } -func (a *Remote) sendPush(m pendingMessage, userID string, sv *cluster.Server) (err error) { +func (a *Remote) sendPush(m pendingMessage, userID string, sv *cluster2.Server) (err error) { payload, err := util.SerializeOrRaw(a.serializer, m.payload) if err != nil { return err @@ -223,7 +223,7 @@ func (a *Remote) SendRequest(ctx context.Context, serverID, reqRoute string, v i if err != nil { return nil, err } - msg := &message.Message{ + msg := &message2.Message{ Route: reqRoute, Data: payload, } diff --git a/agent/agent_remote_test.go b/pkg/agent/agent_remote_test.go similarity index 86% rename from agent/agent_remote_test.go rename to pkg/agent/agent_remote_test.go index 3bb6ad89..2c6bb67e 100644 --- a/agent/agent_remote_test.go +++ b/pkg/agent/agent_remote_test.go @@ -23,6 +23,13 @@ package agent import ( "context" "errors" + cluster2 "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/cluster/mocks" + codecmocks "github.com/topfreegames/pitaya/v3/pkg/conn/codec/mocks" + message2 "github.com/topfreegames/pitaya/v3/pkg/conn/message" + messagemocks "github.com/topfreegames/pitaya/v3/pkg/conn/message/mocks" + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" + "github.com/topfreegames/pitaya/v3/pkg/constants" "math/rand" "reflect" "testing" @@ -30,17 +37,10 @@ import ( "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/cluster" - clustermocks "github.com/topfreegames/pitaya/v2/cluster/mocks" - codecmocks "github.com/topfreegames/pitaya/v2/conn/codec/mocks" - "github.com/topfreegames/pitaya/v2/conn/message" - messagemocks "github.com/topfreegames/pitaya/v2/conn/message/mocks" - "github.com/topfreegames/pitaya/v2/conn/packet" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/route" - serializemocks "github.com/topfreegames/pitaya/v2/serialize/mocks" - "github.com/topfreegames/pitaya/v2/session" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" + serializemocks "github.com/topfreegames/pitaya/v3/pkg/serialize/mocks" + "github.com/topfreegames/pitaya/v3/pkg/session" ) type someStruct struct { @@ -56,8 +56,8 @@ func TestNewRemote(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockRPCClient := clustermocks.NewMockRPCClient(ctrl) - mockSD := clustermocks.NewMockServiceDiscovery(ctrl) + mockRPCClient := mocks.NewMockRPCClient(ctrl) + mockSD := mocks.NewMockServiceDiscovery(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) @@ -108,13 +108,13 @@ func TestAgentRemotePush(t *testing.T) { route := uuid.New().String() tables := []struct { name string - uid string - rpcClient cluster.RPCClient - data interface{} + uid string + rpcClient cluster2.RPCClient + data interface{} errSerialize error err error }{ - {"nats_rpc_session_not_bound", "", &cluster.NatsRPCClient{}, nil, nil, constants.ErrNoUIDBind}, + {"nats_rpc_session_not_bound", "", &cluster2.NatsRPCClient{}, nil, nil, constants.ErrNoUIDBind}, {"success_raw_message", uuid.New().String(), nil, []byte("ok"), nil, nil}, {"failed_struct_message_serialize", uuid.New().String(), nil, &someStruct{A: "ok"}, errors.New("failed serialize"), errors.New("failed serialize")}, {"success_struct_message", uuid.New().String(), nil, &someStruct{A: "ok"}, nil, nil}, @@ -127,12 +127,12 @@ func TestAgentRemotePush(t *testing.T) { defer ctrl.Finish() if table.rpcClient == nil { - table.rpcClient = clustermocks.NewMockRPCClient(ctrl) + table.rpcClient = mocks.NewMockRPCClient(ctrl) } fSvID := "123id" ss := &protos.Session{Uid: table.uid} mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockSD := clustermocks.NewMockServiceDiscovery(ctrl) + mockSD := mocks.NewMockServiceDiscovery(ctrl) sessionPool := session.NewSessionPool() remote, err := NewRemote(ss, "", table.rpcClient, nil, mockSerializer, mockSD, fSvID, nil, sessionPool) assert.NoError(t, err) @@ -153,12 +153,12 @@ func TestAgentRemotePush(t *testing.T) { Uid: table.uid, Data: expectedData, } - table.rpcClient.(*clustermocks.MockRPCClient).EXPECT().SendPush(table.uid, gomock.Any(), expectedPush).Return(table.err) + table.rpcClient.(*mocks.MockRPCClient).EXPECT().SendPush(table.uid, gomock.Any(), expectedPush).Return(table.err) } } if table.err != constants.ErrNoUIDBind { - mockSD.EXPECT().GetServer(fSvID).Return(cluster.NewServer(fSvID, "connector", true), nil) + mockSD.EXPECT().GetServer(fSvID).Return(cluster2.NewServer(fSvID, "connector", true), nil) } err = remote.Push(route, table.data) assert.Equal(t, table.err, err) @@ -170,9 +170,9 @@ func TestKickRemote(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - rpcClient := clustermocks.NewMockRPCClient(ctrl) + rpcClient := mocks.NewMockRPCClient(ctrl) ss := &protos.Session{Uid: uuid.New().String()} - mockSD := clustermocks.NewMockServiceDiscovery(ctrl) + mockSD := mocks.NewMockServiceDiscovery(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) frontID := uuid.New().String() @@ -218,8 +218,8 @@ func TestAgentRemoteResponseMID(t *testing.T) { ss := &protos.Session{Uid: uid} mockEnconder := codecmocks.NewMockPacketEncoder(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockRPCClient := clustermocks.NewMockRPCClient(ctrl) - messageEncoder := message.NewMessagesEncoder(false) + mockRPCClient := mocks.NewMockRPCClient(ctrl) + messageEncoder := message2.NewMessagesEncoder(false) sessionPool := session.NewSessionPool() remote, err := NewRemote(ss, reply, mockRPCClient, mockEnconder, mockSerializer, nil, "", messageEncoder, sessionPool) assert.NoError(t, err) @@ -234,8 +234,8 @@ func TestAgentRemoteResponseMID(t *testing.T) { } if table.errSerialize == nil { - rawMsg := &message.Message{ - Type: message.Response, + rawMsg := &message2.Message{ + Type: message2.Response, Data: serializeRet, ID: table.mid, Err: table.msgErr, @@ -287,9 +287,9 @@ func TestAgentRemoteSendRequest(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockSD := clustermocks.NewMockServiceDiscovery(ctrl) + mockSD := mocks.NewMockServiceDiscovery(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockRPCClient := clustermocks.NewMockRPCClient(ctrl) + mockRPCClient := mocks.NewMockRPCClient(ctrl) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) sessionPool := session.NewSessionPool() remote, err := NewRemote(nil, "", mockRPCClient, nil, mockSerializer, mockSD, "", mockMessageEncoder, sessionPool) @@ -307,12 +307,12 @@ func TestAgentRemoteSendRequest(t *testing.T) { } if table.errSerialize == nil { - expectedServer := &cluster.Server{} + expectedServer := &cluster2.Server{} mockSD.EXPECT().GetServer(table.serverID).Return(expectedServer, table.errGetServer) if table.errGetServer == nil { r, _ := route.Decode(table.reqRoute) - expectedMsg := &message.Message{ + expectedMsg := &message2.Message{ Route: table.reqRoute, Data: serializeRet, } diff --git a/agent/agent_test.go b/pkg/agent/agent_test.go similarity index 86% rename from agent/agent_test.go rename to pkg/agent/agent_test.go index 3f76037a..69abe061 100644 --- a/agent/agent_test.go +++ b/pkg/agent/agent_test.go @@ -24,6 +24,13 @@ import ( "context" "errors" "fmt" + mocks2 "github.com/topfreegames/pitaya/v3/pkg/conn/codec/mocks" + message2 "github.com/topfreegames/pitaya/v3/pkg/conn/message" + messagemocks "github.com/topfreegames/pitaya/v3/pkg/conn/message/mocks" + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "math/rand" "reflect" "sync" @@ -33,20 +40,13 @@ import ( "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/stretchr/testify/assert" - codecmocks "github.com/topfreegames/pitaya/v2/conn/codec/mocks" - "github.com/topfreegames/pitaya/v2/conn/message" - messagemocks "github.com/topfreegames/pitaya/v2/conn/message/mocks" - "github.com/topfreegames/pitaya/v2/conn/packet" - "github.com/topfreegames/pitaya/v2/constants" - pcontext "github.com/topfreegames/pitaya/v2/context" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/helpers" - "github.com/topfreegames/pitaya/v2/metrics" - metricsmocks "github.com/topfreegames/pitaya/v2/metrics/mocks" - "github.com/topfreegames/pitaya/v2/mocks" - "github.com/topfreegames/pitaya/v2/protos" - serializemocks "github.com/topfreegames/pitaya/v2/serialize/mocks" - "github.com/topfreegames/pitaya/v2/session" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + metricsmocks "github.com/topfreegames/pitaya/v3/pkg/metrics/mocks" + "github.com/topfreegames/pitaya/v3/pkg/mocks" + "github.com/topfreegames/pitaya/v3/pkg/protos" + serializemocks "github.com/topfreegames/pitaya/v3/pkg/serialize/mocks" + "github.com/topfreegames/pitaya/v3/pkg/session" ) type mockAddr struct{} @@ -54,15 +54,15 @@ type mockAddr struct{} func (m *mockAddr) Network() string { return "" } func (m *mockAddr) String() string { return "remote-string" } -func heartbeatAndHandshakeMocks(mockEncoder *codecmocks.MockPacketEncoder) { +func heartbeatAndHandshakeMocks(mockEncoder *mocks2.MockPacketEncoder) { // heartbeat and handshake if not set by another test mockEncoder.EXPECT().Encode(packet.Type(packet.Handshake), gomock.Not(gomock.Nil())).AnyTimes() mockEncoder.EXPECT().Encode(packet.Type(packet.Heartbeat), gomock.Nil()).AnyTimes() } func getCtxWithRequestKeys() context.Context { - ctx := pcontext.AddToPropagateCtx(context.Background(), constants.StartTimeKey, time.Now().UnixNano()) - return pcontext.AddToPropagateCtx(ctx, constants.RouteKey, "route") + ctx := pcontext.AddToPropagateCtx(context.Background(), constants2.StartTimeKey, time.Now().UnixNano()) + return pcontext.AddToPropagateCtx(ctx, constants2.RouteKey, "route") } func TestNewAgent(t *testing.T) { @@ -73,8 +73,8 @@ func TestNewAgent(t *testing.T) { mockSerializer.EXPECT().GetName().Times(2) mockMetricsReporter := metricsmocks.NewMockReporter(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) - mockDecoder := codecmocks.NewMockPacketDecoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) + mockDecoder := mocks2.NewMockPacketDecoder(ctrl) dieChan := make(chan bool) hbTime := time.Second @@ -89,7 +89,7 @@ func TestNewAgent(t *testing.T) { func(typ packet.Type, d []byte) { assert.EqualValues(t, packet.Heartbeat, typ) }) - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockMetricsReporters := []metrics.Reporter{mockMetricsReporter} sessionPool := session.NewSessionPool() @@ -110,7 +110,7 @@ func TestNewAgent(t *testing.T) { assert.InDelta(t, time.Now().Unix(), ag.lastAt, 1) assert.Equal(t, mockSerializer, ag.serializer) assert.Equal(t, mockMetricsReporters, ag.metricsReporters) - assert.Equal(t, constants.StatusStart, ag.state) + assert.Equal(t, constants2.StatusStart, ag.state) assert.NotNil(t, ag.Session) assert.True(t, ag.Session.GetIsFrontend()) @@ -125,8 +125,8 @@ func TestKick(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) - mockDecoder := codecmocks.NewMockPacketDecoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) + mockDecoder := mocks2.NewMockPacketDecoder(ctrl) dieChan := make(chan bool) hbTime := time.Second @@ -136,7 +136,7 @@ func TestKick(t *testing.T) { assert.EqualValues(t, packet.Kick, typ) }) mockConn.EXPECT().Write(gomock.Any()).Return(0, nil) - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockSerializer.EXPECT().GetName() @@ -153,7 +153,7 @@ func TestAgentSend(t *testing.T) { err error }{ {"success", nil}, - {"failure", e.NewError(constants.ErrBrokenPipe, e.ErrClientClosedRequest)}, + {"failure", e.NewError(constants2.ErrBrokenPipe, e.ErrClientClosedRequest)}, } for _, table := range tables { @@ -162,12 +162,12 @@ func TestAgentSend(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) - mockDecoder := codecmocks.NewMockPacketDecoder(ctrl) + mockDecoder := mocks2.NewMockPacketDecoder(ctrl) dieChan := make(chan bool) hbTime := time.Second - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockConn := mocks.NewMockPlayerConn(ctrl) mockSerializer.EXPECT().GetName() @@ -208,8 +208,8 @@ func TestAgentSendSerializeErr(t *testing.T) { mockConn := mocks.NewMockPlayerConn(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) - messageEncoder := message.NewMessagesEncoder(false) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) + messageEncoder := message2.NewMessagesEncoder(false) mockMetricsReporter := metricsmocks.NewMockReporter(ctrl) mockMetricsReporters := []metrics.Reporter{mockMetricsReporter} sessionPool := session.NewSessionPool() @@ -230,7 +230,7 @@ func TestAgentSendSerializeErr(t *testing.T) { expected := pendingMessage{ ctx: ctx, - typ: message.Response, + typ: message2.Response, route: uuid.New().String(), mid: uint(rand.Int()), payload: someStruct{A: "bla"}, @@ -243,7 +243,7 @@ func TestAgentSendSerializeErr(t *testing.T) { Code: e.ErrUnknownCode, Msg: expectedErr.Error(), }).Return(expectedBT, nil) - m := &message.Message{ + m := &message2.Message{ Type: expected.typ, Data: expectedBT, Route: expected.route, @@ -275,16 +275,16 @@ func TestAgentPushFailsIfClosedAgent(t *testing.T) { mockSerializer := serializemocks.NewMockSerializer(ctrl) mockSerializer.EXPECT().GetName() - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) sessionPool := session.NewSessionPool() ag := newAgent(nil, nil, mockEncoder, mockSerializer, time.Second, 10, nil, messageEncoder, nil, sessionPool).(*agentImpl) assert.NotNil(t, ag) - ag.state = constants.StatusClosed + ag.state = constants2.StatusClosed err := ag.Push("", nil) - assert.Equal(t, e.NewError(constants.ErrBrokenPipe, e.ErrClientClosedRequest), err) + assert.Equal(t, e.NewError(constants2.ErrBrokenPipe, e.ErrClientClosedRequest), err) } func TestAgentPushStruct(t *testing.T) { @@ -302,12 +302,12 @@ func TestAgentPushStruct(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) - mockDecoder := codecmocks.NewMockPacketDecoder(ctrl) + mockDecoder := mocks2.NewMockPacketDecoder(ctrl) dieChan := make(chan bool) hbTime := time.Second - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockMetricsReporter := metricsmocks.NewMockReporter(ctrl) mockConn := mocks.NewMockPlayerConn(ctrl) mockMetricsReporters := []metrics.Reporter{mockMetricsReporter} @@ -318,8 +318,8 @@ func TestAgentPushStruct(t *testing.T) { assert.NotNil(t, ag) expectedBytes := []byte("hello") - msg := &message.Message{ - Type: message.Push, + msg := &message2.Message{ + Type: message2.Push, Route: uuid.New().String(), Data: expectedBytes, } @@ -352,7 +352,7 @@ func TestAgentPush(t *testing.T) { err error }{ {"success_raw", []byte("ok"), nil}, - {"failure", []byte("ok"), e.NewError(constants.ErrBrokenPipe, e.ErrClientClosedRequest)}, + {"failure", []byte("ok"), e.NewError(constants2.ErrBrokenPipe, e.ErrClientClosedRequest)}, } for _, table := range tables { @@ -361,12 +361,12 @@ func TestAgentPush(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) - mockDecoder := codecmocks.NewMockPacketDecoder(ctrl) + mockDecoder := mocks2.NewMockPacketDecoder(ctrl) dieChan := make(chan bool) hbTime := time.Second - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockMetricsReporter := metricsmocks.NewMockReporter(ctrl) mockConn := mocks.NewMockPlayerConn(ctrl) mockMetricsReporters := []metrics.Reporter{mockMetricsReporter} @@ -377,8 +377,8 @@ func TestAgentPush(t *testing.T) { assert.NotNil(t, ag) expectedBytes := []byte("hello") - msg := &message.Message{ - Type: message.Push, + msg := &message2.Message{ + Type: message2.Push, Route: uuid.New().String(), Data: table.data, } @@ -408,12 +408,12 @@ func TestAgentPushFullChannel(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) - mockDecoder := codecmocks.NewMockPacketDecoder(ctrl) + mockDecoder := mocks2.NewMockPacketDecoder(ctrl) dieChan := make(chan bool) hbTime := time.Second - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockMetricsReporter := metricsmocks.NewMockReporter(ctrl) mockConn := mocks.NewMockPlayerConn(ctrl) mockMetricsReporters := []metrics.Reporter{mockMetricsReporter} @@ -425,10 +425,10 @@ func TestAgentPushFullChannel(t *testing.T) { mockMetricsReporter.EXPECT().ReportGauge(metrics.ChannelCapacity, gomock.Any(), float64(0)) - msg := &message.Message{ + msg := &message2.Message{ Route: "route", Data: []byte("data"), - Type: message.Push, + Type: message2.Push, } em, err := messageEncoder.Encode(msg) assert.NoError(t, err) @@ -445,7 +445,7 @@ func TestAgentResponseMIDFailsIfClosedAgent(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) mockMetricsReporter := metricsmocks.NewMockReporter(ctrl) @@ -458,11 +458,11 @@ func TestAgentResponseMIDFailsIfClosedAgent(t *testing.T) { sessionPool := session.NewSessionPool() ag := newAgent(nil, nil, mockEncoder, mockSerializer, time.Second, 10, nil, mockMessageEncoder, mockMetricsReporters, sessionPool).(*agentImpl) assert.NotNil(t, ag) - ag.state = constants.StatusClosed + ag.state = constants2.StatusClosed ctx := getCtxWithRequestKeys() err := ag.ResponseMID(ctx, 1, nil) - assert.Equal(t, e.NewError(constants.ErrBrokenPipe, e.ErrClientClosedRequest), err) + assert.Equal(t, e.NewError(constants2.ErrBrokenPipe, e.ErrClientClosedRequest), err) } func TestAgentResponseMID(t *testing.T) { @@ -476,9 +476,9 @@ func TestAgentResponseMID(t *testing.T) { {"success_raw", uint(rand.Int()), []byte("ok"), false, nil}, {"success_raw_msg_err", uint(rand.Int()), []byte("ok"), true, nil}, {"success_struct", uint(rand.Int()), &someStruct{A: "ok"}, false, nil}, - {"failure_empty_mid", 0, []byte("ok"), false, constants.ErrSessionOnNotify}, + {"failure_empty_mid", 0, []byte("ok"), false, constants2.ErrSessionOnNotify}, {"failure_send", uint(rand.Int()), []byte("ok"), false, - e.NewError(constants.ErrBrokenPipe, e.ErrClientClosedRequest)}, + e.NewError(constants2.ErrBrokenPipe, e.ErrClientClosedRequest)}, } for _, table := range tables { @@ -488,12 +488,12 @@ func TestAgentResponseMID(t *testing.T) { mockMetricsReporter := metricsmocks.NewMockReporter(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) - mockDecoder := codecmocks.NewMockPacketDecoder(ctrl) + mockDecoder := mocks2.NewMockPacketDecoder(ctrl) dieChan := make(chan bool) hbTime := time.Second - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockConn := mocks.NewMockPlayerConn(ctrl) mockMetricsReporters := []metrics.Reporter{mockMetricsReporter} @@ -542,12 +542,12 @@ func TestAgentResponseMIDFullChannel(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) - mockDecoder := codecmocks.NewMockPacketDecoder(ctrl) + mockDecoder := mocks2.NewMockPacketDecoder(ctrl) dieChan := make(chan bool) hbTime := time.Second - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockMetricsReporter := metricsmocks.NewMockReporter(ctrl) mockConn := mocks.NewMockPlayerConn(ctrl) mockMetricsReporters := []metrics.Reporter{mockMetricsReporter} @@ -569,7 +569,7 @@ func TestAgentCloseFailsIfAlreadyClosed(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) @@ -578,9 +578,9 @@ func TestAgentCloseFailsIfAlreadyClosed(t *testing.T) { sessionPool := session.NewSessionPool() ag := newAgent(nil, nil, mockEncoder, mockSerializer, time.Second, 10, nil, mockMessageEncoder, nil, sessionPool).(*agentImpl) assert.NotNil(t, ag) - ag.state = constants.StatusClosed + ag.state = constants2.StatusClosed err := ag.Close() - assert.Equal(t, constants.ErrCloseClosedSession, err) + assert.Equal(t, constants2.ErrCloseClosedSession, err) } func TestAgentClose(t *testing.T) { @@ -588,7 +588,7 @@ func TestAgentClose(t *testing.T) { defer ctrl.Finish() mockConn := mocks.NewMockPlayerConn(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) @@ -624,7 +624,7 @@ func TestAgentClose(t *testing.T) { mockConn.EXPECT().Close() err = ag.Close() assert.NoError(t, err) - assert.Equal(t, ag.state, constants.StatusClosed) + assert.Equal(t, ag.state, constants2.StatusClosed) assert.True(t, expected) helpers.ShouldEventuallyReturn( t, func() bool { return stopWrite && stopHeartbeat && die }, @@ -636,7 +636,7 @@ func TestAgentRemoteAddr(t *testing.T) { defer ctrl.Finish() mockConn := mocks.NewMockPlayerConn(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) @@ -657,7 +657,7 @@ func TestAgentString(t *testing.T) { defer ctrl.Finish() mockConn := mocks.NewMockPlayerConn(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) @@ -678,8 +678,8 @@ func TestAgentGetStatus(t *testing.T) { name string status int32 }{ - {"start", constants.StatusStart}, - {"closed", constants.StatusClosed}, + {"start", constants2.StatusStart}, + {"closed", constants2.StatusClosed}, } for _, table := range tables { @@ -688,7 +688,7 @@ func TestAgentGetStatus(t *testing.T) { defer ctrl.Finish() mockConn := mocks.NewMockPlayerConn(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) @@ -711,7 +711,7 @@ func TestAgentSetLastAt(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) @@ -731,8 +731,8 @@ func TestAgentSetStatus(t *testing.T) { name string status int32 }{ - {"start", constants.StatusStart}, - {"closed", constants.StatusClosed}, + {"start", constants2.StatusStart}, + {"closed", constants2.StatusClosed}, } for _, table := range tables { @@ -740,7 +740,7 @@ func TestAgentSetStatus(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) @@ -759,7 +759,7 @@ func TestAgentSetStatus(t *testing.T) { func TestOnSessionClosed(t *testing.T) { ctrl := gomock.NewController(t) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) @@ -781,7 +781,7 @@ func TestOnSessionClosed(t *testing.T) { func TestOnSessionClosedRecoversIfPanic(t *testing.T) { ctrl := gomock.NewController(t) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) @@ -818,7 +818,7 @@ func TestAgentSendHandshakeResponse(t *testing.T) { defer ctrl.Finish() mockConn := mocks.NewMockPlayerConn(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) mockSerializer := serializemocks.NewMockSerializer(ctrl) @@ -853,9 +853,9 @@ func TestAnswerWithError(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockSerializer.EXPECT().GetName() sessionPool := session.NewSessionPool() ag := newAgent(nil, nil, mockEncoder, mockSerializer, time.Second, 1, nil, messageEncoder, nil, sessionPool).(*agentImpl) @@ -878,7 +878,7 @@ func TestAgentHeartbeat(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockConn := mocks.NewMockPlayerConn(ctrl) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) @@ -913,7 +913,7 @@ func TestAgentHeartbeatExitsIfConnError(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockConn := mocks.NewMockPlayerConn(ctrl) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) @@ -949,10 +949,10 @@ func TestAgentHeartbeatExitsOnStopHeartbeat(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockConn := mocks.NewMockPlayerConn(ctrl) - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockConn.EXPECT().RemoteAddr().MaxTimes(1) mockConn.EXPECT().Close().MaxTimes(1) @@ -975,9 +975,9 @@ func TestAgentWriteChSend(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) mockConn := mocks.NewMockPlayerConn(ctrl) - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockMetricsReporter := metricsmocks.NewMockReporter(ctrl) mockMetricsReporters := []metrics.Reporter{mockMetricsReporter} ag := &agentImpl{ // avoid heartbeat and handshake to fully test serialize @@ -1010,10 +1010,10 @@ func TestAgentHandle(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) mockConn := mocks.NewMockPlayerConn(ctrl) - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockSerializer.EXPECT().GetName() sessionPool := session.NewSessionPool() ag := newAgent(mockConn, nil, mockEncoder, mockSerializer, 1*time.Second, 1, nil, messageEncoder, nil, sessionPool).(*agentImpl) @@ -1055,12 +1055,12 @@ func TestNatsRPCServerReportMetrics(t *testing.T) { defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockEncoder := codecmocks.NewMockPacketEncoder(ctrl) + mockEncoder := mocks2.NewMockPacketEncoder(ctrl) heartbeatAndHandshakeMocks(mockEncoder) - mockDecoder := codecmocks.NewMockPacketDecoder(ctrl) + mockDecoder := mocks2.NewMockPacketDecoder(ctrl) dieChan := make(chan bool) hbTime := time.Second - messageEncoder := message.NewMessagesEncoder(false) + messageEncoder := message2.NewMessagesEncoder(false) mockMetricsReporter := metricsmocks.NewMockReporter(ctrl) mockMetricsReporters := []metrics.Reporter{mockMetricsReporter} mockConn := mocks.NewMockPlayerConn(ctrl) @@ -1088,10 +1088,10 @@ func TestIPVersion(t *testing.T) { addr string ipVersion string }{ - {"127.0.0.1:80", constants.IPv4}, - {"1.2.3.4:3333", constants.IPv4}, - {"::1:3333", constants.IPv6}, - {"2001:db8:0000:1:1:1:1:1:3333", constants.IPv6}, + {"127.0.0.1:80", constants2.IPv4}, + {"1.2.3.4:3333", constants2.IPv4}, + {"::1:3333", constants2.IPv6}, + {"2001:db8:0000:1:1:1:1:1:3333", constants2.IPv6}, } for _, table := range tables { diff --git a/pkg/agent/mocks/agent.go b/pkg/agent/mocks/agent.go new file mode 100644 index 00000000..65ed612c --- /dev/null +++ b/pkg/agent/mocks/agent.go @@ -0,0 +1,284 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/topfreegames/pitaya/v3/pkg/agent (interfaces: Agent,AgentFactory) + +// Package mocks is a generated GoMock package. +package mocks + +import ( + context "context" + net "net" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + agent "github.com/topfreegames/pitaya/v3/pkg/agent" + protos "github.com/topfreegames/pitaya/v3/pkg/protos" + session "github.com/topfreegames/pitaya/v3/pkg/session" +) + +// MockAgent is a mock of Agent interface. +type MockAgent struct { + ctrl *gomock.Controller + recorder *MockAgentMockRecorder +} + +// MockAgentMockRecorder is the mock recorder for MockAgent. +type MockAgentMockRecorder struct { + mock *MockAgent +} + +// NewMockAgent creates a new mock instance. +func NewMockAgent(ctrl *gomock.Controller) *MockAgent { + mock := &MockAgent{ctrl: ctrl} + mock.recorder = &MockAgentMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockAgent) EXPECT() *MockAgentMockRecorder { + return m.recorder +} + +// AnswerWithError mocks base method. +func (m *MockAgent) AnswerWithError(arg0 context.Context, arg1 uint, arg2 error) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AnswerWithError", arg0, arg1, arg2) +} + +// AnswerWithError indicates an expected call of AnswerWithError. +func (mr *MockAgentMockRecorder) AnswerWithError(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AnswerWithError", reflect.TypeOf((*MockAgent)(nil).AnswerWithError), arg0, arg1, arg2) +} + +// Close mocks base method. +func (m *MockAgent) Close() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Close") + ret0, _ := ret[0].(error) + return ret0 +} + +// Close indicates an expected call of Close. +func (mr *MockAgentMockRecorder) Close() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockAgent)(nil).Close)) +} + +// GetSession mocks base method. +func (m *MockAgent) GetSession() session.Session { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSession") + ret0, _ := ret[0].(session.Session) + return ret0 +} + +// GetSession indicates an expected call of GetSession. +func (mr *MockAgentMockRecorder) GetSession() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSession", reflect.TypeOf((*MockAgent)(nil).GetSession)) +} + +// GetStatus mocks base method. +func (m *MockAgent) GetStatus() int32 { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetStatus") + ret0, _ := ret[0].(int32) + return ret0 +} + +// GetStatus indicates an expected call of GetStatus. +func (mr *MockAgentMockRecorder) GetStatus() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStatus", reflect.TypeOf((*MockAgent)(nil).GetStatus)) +} + +// Handle mocks base method. +func (m *MockAgent) Handle() { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Handle") +} + +// Handle indicates an expected call of Handle. +func (mr *MockAgentMockRecorder) Handle() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Handle", reflect.TypeOf((*MockAgent)(nil).Handle)) +} + +// IPVersion mocks base method. +func (m *MockAgent) IPVersion() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "IPVersion") + ret0, _ := ret[0].(string) + return ret0 +} + +// IPVersion indicates an expected call of IPVersion. +func (mr *MockAgentMockRecorder) IPVersion() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IPVersion", reflect.TypeOf((*MockAgent)(nil).IPVersion)) +} + +// Kick mocks base method. +func (m *MockAgent) Kick(arg0 context.Context) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Kick", arg0) + ret0, _ := ret[0].(error) + return ret0 +} + +// Kick indicates an expected call of Kick. +func (mr *MockAgentMockRecorder) Kick(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Kick", reflect.TypeOf((*MockAgent)(nil).Kick), arg0) +} + +// Push mocks base method. +func (m *MockAgent) Push(arg0 string, arg1 interface{}) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Push", arg0, arg1) + ret0, _ := ret[0].(error) + return ret0 +} + +// Push indicates an expected call of Push. +func (mr *MockAgentMockRecorder) Push(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Push", reflect.TypeOf((*MockAgent)(nil).Push), arg0, arg1) +} + +// RemoteAddr mocks base method. +func (m *MockAgent) RemoteAddr() net.Addr { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RemoteAddr") + ret0, _ := ret[0].(net.Addr) + return ret0 +} + +// RemoteAddr indicates an expected call of RemoteAddr. +func (mr *MockAgentMockRecorder) RemoteAddr() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoteAddr", reflect.TypeOf((*MockAgent)(nil).RemoteAddr)) +} + +// ResponseMID mocks base method. +func (m *MockAgent) ResponseMID(arg0 context.Context, arg1 uint, arg2 interface{}, arg3 ...bool) error { + m.ctrl.T.Helper() + varargs := []interface{}{arg0, arg1, arg2} + for _, a := range arg3 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ResponseMID", varargs...) + ret0, _ := ret[0].(error) + return ret0 +} + +// ResponseMID indicates an expected call of ResponseMID. +func (mr *MockAgentMockRecorder) ResponseMID(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{arg0, arg1, arg2}, arg3...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResponseMID", reflect.TypeOf((*MockAgent)(nil).ResponseMID), varargs...) +} + +// SendHandshakeResponse mocks base method. +func (m *MockAgent) SendHandshakeResponse() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendHandshakeResponse") + ret0, _ := ret[0].(error) + return ret0 +} + +// SendHandshakeResponse indicates an expected call of SendHandshakeResponse. +func (mr *MockAgentMockRecorder) SendHandshakeResponse() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendHandshakeResponse", reflect.TypeOf((*MockAgent)(nil).SendHandshakeResponse)) +} + +// SendRequest mocks base method. +func (m *MockAgent) SendRequest(arg0 context.Context, arg1, arg2 string, arg3 interface{}) (*protos.Response, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendRequest", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(*protos.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// SendRequest indicates an expected call of SendRequest. +func (mr *MockAgentMockRecorder) SendRequest(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendRequest", reflect.TypeOf((*MockAgent)(nil).SendRequest), arg0, arg1, arg2, arg3) +} + +// SetLastAt mocks base method. +func (m *MockAgent) SetLastAt() { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetLastAt") +} + +// SetLastAt indicates an expected call of SetLastAt. +func (mr *MockAgentMockRecorder) SetLastAt() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastAt", reflect.TypeOf((*MockAgent)(nil).SetLastAt)) +} + +// SetStatus mocks base method. +func (m *MockAgent) SetStatus(arg0 int32) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetStatus", arg0) +} + +// SetStatus indicates an expected call of SetStatus. +func (mr *MockAgentMockRecorder) SetStatus(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetStatus", reflect.TypeOf((*MockAgent)(nil).SetStatus), arg0) +} + +// String mocks base method. +func (m *MockAgent) String() string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "String") + ret0, _ := ret[0].(string) + return ret0 +} + +// String indicates an expected call of String. +func (mr *MockAgentMockRecorder) String() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "String", reflect.TypeOf((*MockAgent)(nil).String)) +} + +// MockAgentFactory is a mock of AgentFactory interface. +type MockAgentFactory struct { + ctrl *gomock.Controller + recorder *MockAgentFactoryMockRecorder +} + +// MockAgentFactoryMockRecorder is the mock recorder for MockAgentFactory. +type MockAgentFactoryMockRecorder struct { + mock *MockAgentFactory +} + +// NewMockAgentFactory creates a new mock instance. +func NewMockAgentFactory(ctrl *gomock.Controller) *MockAgentFactory { + mock := &MockAgentFactory{ctrl: ctrl} + mock.recorder = &MockAgentFactoryMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockAgentFactory) EXPECT() *MockAgentFactoryMockRecorder { + return m.recorder +} + +// CreateAgent mocks base method. +func (m *MockAgentFactory) CreateAgent(arg0 net.Conn) agent.Agent { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateAgent", arg0) + ret0, _ := ret[0].(agent.Agent) + return ret0 +} + +// CreateAgent indicates an expected call of CreateAgent. +func (mr *MockAgentFactoryMockRecorder) CreateAgent(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateAgent", reflect.TypeOf((*MockAgentFactory)(nil).CreateAgent), arg0) +} diff --git a/app.go b/pkg/app.go similarity index 81% rename from app.go rename to pkg/app.go index a5fe0b08..471fc0f5 100644 --- a/app.go +++ b/pkg/app.go @@ -18,43 +18,45 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + cluster2 "github.com/topfreegames/pitaya/v3/pkg/cluster" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" + "github.com/topfreegames/pitaya/v3/pkg/docgenerator" + "github.com/topfreegames/pitaya/v3/pkg/errors" + "github.com/topfreegames/pitaya/v3/pkg/groups" "os" "os/signal" "reflect" "strings" + "sync" "syscall" "time" "github.com/golang/protobuf/proto" opentracing "github.com/opentracing/opentracing-go" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - pcontext "github.com/topfreegames/pitaya/v2/context" - "github.com/topfreegames/pitaya/v2/docgenerator" - "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/groups" - "github.com/topfreegames/pitaya/v2/interfaces" - "github.com/topfreegames/pitaya/v2/logger" - logging "github.com/topfreegames/pitaya/v2/logger/interfaces" - "github.com/topfreegames/pitaya/v2/metrics" - mods "github.com/topfreegames/pitaya/v2/modules" - "github.com/topfreegames/pitaya/v2/remote" - "github.com/topfreegames/pitaya/v2/router" - "github.com/topfreegames/pitaya/v2/serialize" - "github.com/topfreegames/pitaya/v2/service" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/timer" - "github.com/topfreegames/pitaya/v2/tracing" - "github.com/topfreegames/pitaya/v2/worker" + "github.com/topfreegames/pitaya/v3/pkg/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/logger" + logging "github.com/topfreegames/pitaya/v3/pkg/logger/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + mods "github.com/topfreegames/pitaya/v3/pkg/modules" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/remote" + "github.com/topfreegames/pitaya/v3/pkg/router" + "github.com/topfreegames/pitaya/v3/pkg/serialize" + "github.com/topfreegames/pitaya/v3/pkg/service" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/timer" + "github.com/topfreegames/pitaya/v3/pkg/tracing" + "github.com/topfreegames/pitaya/v3/pkg/worker" ) // ServerMode represents a server mode @@ -75,20 +77,21 @@ type Pitaya interface { SetHeartbeatTime(interval time.Duration) GetServerID() string GetMetricsReporters() []metrics.Reporter - GetServer() *cluster.Server - GetServerByID(id string) (*cluster.Server, error) - GetServersByType(t string) (map[string]*cluster.Server, error) - GetServers() []*cluster.Server + GetServer() *cluster2.Server + GetServerByID(id string) (*cluster2.Server, error) + GetServersByType(t string) (map[string]*cluster2.Server, error) + GetServers() []*cluster2.Server GetSessionFromCtx(ctx context.Context) session.Session Start() SetDictionary(dict map[string]uint16) error AddRoute(serverType string, routingFunction router.RoutingFunc) error - Shutdown() + Shutdown() *sync.WaitGroup StartWorker() RegisterRPCJob(rpcJob worker.RPCJob) error Documentation(getPtrNames bool) (map[string]interface{}, error) IsRunning() bool + RawRPC(ctx context.Context, serverID, routeStr string, arg []byte) (*protos.Response, error) RPC(ctx context.Context, routeStr string, reply proto.Message, arg proto.Message) error RPCTo(ctx context.Context, serverID, routeStr string, reply proto.Message, arg proto.Message) error ReliableRPC( @@ -118,8 +121,8 @@ type Pitaya interface { GroupRenewTTL(ctx context.Context, groupName string) error GroupDelete(ctx context.Context, groupName string) error - Register(c component.Component, options ...component.Option) - RegisterRemote(c component.Component, options ...component.Option) + Register(c component2.Component, options ...component2.Option) + RegisterRemote(c component2.Component, options ...component2.Option) RegisterModule(module interfaces.Module, name string) error RegisterModuleAfter(module interfaces.Module, name string) error @@ -133,17 +136,18 @@ type App struct { config config.PitayaConfig debug bool dieChan chan bool + wgIsRunning sync.WaitGroup heartbeat time.Duration onSessionBind func(session.Session) router *router.Router - rpcClient cluster.RPCClient - rpcServer cluster.RPCServer + rpcClient cluster2.RPCClient + rpcServer cluster2.RPCServer metricsReporters []metrics.Reporter running bool serializer serialize.Serializer - server *cluster.Server + server *cluster2.Server serverMode ServerMode - serviceDiscovery cluster.ServiceDiscovery + serviceDiscovery cluster2.ServiceDiscovery startAt time.Time worker *worker.Worker remoteService *service.RemoteService @@ -163,11 +167,11 @@ func NewApp( acceptors []acceptor.Acceptor, dieChan chan bool, router *router.Router, - server *cluster.Server, - rpcClient cluster.RPCClient, - rpcServer cluster.RPCServer, + server *cluster2.Server, + rpcClient cluster2.RPCClient, + rpcServer cluster2.RPCServer, worker *worker.Worker, - serviceDiscovery cluster.ServiceDiscovery, + serviceDiscovery cluster2.ServiceDiscovery, remoteService *service.RemoteService, handlerService *service.HandlerService, groups groups.GroupService, @@ -234,22 +238,22 @@ func (app *App) GetMetricsReporters() []metrics.Reporter { } // GetServer gets the local server instance -func (app *App) GetServer() *cluster.Server { +func (app *App) GetServer() *cluster2.Server { return app.server } // GetServerByID returns the server with the specified id -func (app *App) GetServerByID(id string) (*cluster.Server, error) { +func (app *App) GetServerByID(id string) (*cluster2.Server, error) { return app.serviceDiscovery.GetServer(id) } // GetServersByType get all servers of type -func (app *App) GetServersByType(t string) (map[string]*cluster.Server, error) { +func (app *App) GetServersByType(t string) (map[string]*cluster2.Server, error) { return app.serviceDiscovery.GetServersByType(t) } // GetServers get all servers -func (app *App) GetServers() []*cluster.Server { +func (app *App) GetServers() []*cluster2.Server { return app.serviceDiscovery.GetServers() } @@ -268,8 +272,8 @@ func SetLogger(l logging.Logger) { func (app *App) initSysRemotes() { sys := remote.NewSys(app.sessionPool) app.RegisterRemote(sys, - component.WithName("sys"), - component.WithNameFunc(strings.ToLower), + component2.WithName("sys"), + component2.WithNameFunc(strings.ToLower), ) } @@ -293,8 +297,8 @@ func (app *App) Start() { } if app.serverMode == Cluster { - if reflect.TypeOf(app.rpcClient) == reflect.TypeOf(&cluster.GRPCClient{}) { - app.serviceDiscovery.AddListener(app.rpcClient.(*cluster.GRPCClient)) + if reflect.TypeOf(app.rpcClient) == reflect.TypeOf(&cluster2.GRPCClient{}) { + app.serviceDiscovery.AddListener(app.rpcClient.(*cluster2.GRPCClient)) } if err := app.RegisterModuleBefore(app.rpcServer, "rpcServer"); err != nil { @@ -315,9 +319,11 @@ func (app *App) Start() { app.listen() + app.wgIsRunning.Add(1) defer func() { timer.GlobalTicker.Stop() app.running = false + app.wgIsRunning.Done() }() sg := make(chan os.Signal) @@ -329,7 +335,7 @@ func (app *App) Start() { logger.Log.Warn("the app will shutdown in a few seconds") case s := <-sg: logger.Log.Warn("got signal: ", s, ", shutting down...") - close(app.dieChan) + Shutdown() } logger.Log.Warn("server is stopping...") @@ -380,7 +386,7 @@ func (app *App) listen() { // SetDictionary sets routes map func (app *App) SetDictionary(dict map[string]uint16) error { if app.running { - return constants.ErrChangeDictionaryWhileRunning + return constants2.ErrChangeDictionaryWhileRunning } return message.SetDictionary(dict) } @@ -392,22 +398,23 @@ func (app *App) AddRoute( ) error { if app.router != nil { if app.running { - return constants.ErrChangeRouteWhileRunning + return constants2.ErrChangeRouteWhileRunning } app.router.AddRoute(serverType, routingFunction) } else { - return constants.ErrRouterNotInitialized + return constants2.ErrRouterNotInitialized } return nil } // Shutdown send a signal to let 'pitaya' shutdown itself. -func (app *App) Shutdown() { +func (app *App) Shutdown() *sync.WaitGroup{ select { case <-app.dieChan: // prevent closing closed channel default: close(app.dieChan) } + return &app.wgIsRunning } // Error creates a new error with a code, message and metadata @@ -417,7 +424,7 @@ func Error(err error, code string, metadata ...map[string]string) *errors.Error // GetSessionFromCtx retrieves a session from a given context func (app *App) GetSessionFromCtx(ctx context.Context) session.Session { - sessionVal := ctx.Value(constants.SessionCtxKey) + sessionVal := ctx.Value(constants2.SessionCtxKey) if sessionVal == nil { logger.Log.Debug("ctx doesn't contain a session, are you calling GetSessionFromCtx from inside a remote?") return nil @@ -427,7 +434,7 @@ func (app *App) GetSessionFromCtx(ctx context.Context) session.Session { // GetDefaultLoggerFromCtx returns the default logger from the given context func GetDefaultLoggerFromCtx(ctx context.Context) logging.Logger { - l := ctx.Value(constants.LoggerCtxKey) + l := ctx.Value(constants2.LoggerCtxKey) if l == nil { return logger.Log } @@ -442,7 +449,7 @@ func AddMetricTagsToPropagateCtx( ctx context.Context, tags map[string]string, ) context.Context { - return pcontext.AddToPropagateCtx(ctx, constants.MetricTagsKey, tags) + return pcontext.AddToPropagateCtx(ctx, constants2.MetricTagsKey, tags) } // AddToPropagateCtx adds a key and value that will be propagated through RPC calls @@ -485,11 +492,11 @@ func AddGRPCInfoToMetadata( host, port string, externalHost, externalPort string, ) map[string]string { - metadata[constants.GRPCHostKey] = host - metadata[constants.GRPCPortKey] = port - metadata[constants.GRPCExternalHostKey] = externalHost - metadata[constants.GRPCExternalPortKey] = externalPort - metadata[constants.RegionKey] = region + metadata[constants2.GRPCHostKey] = host + metadata[constants2.GRPCPortKey] = port + metadata[constants2.GRPCExternalHostKey] = externalHost + metadata[constants2.GRPCExternalPortKey] = externalPort + metadata[constants2.RegionKey] = region return metadata } diff --git a/app_test.go b/pkg/app_test.go similarity index 85% rename from app_test.go rename to pkg/app_test.go index 801b35ad..d299ba68 100644 --- a/app_test.go +++ b/pkg/app_test.go @@ -18,12 +18,18 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "context" "errors" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + cluster2 "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "net" "os" "reflect" @@ -35,19 +41,13 @@ import ( opentracing "github.com/opentracing/opentracing-go" "github.com/spf13/viper" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/helpers" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/logger/logrus" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/router" - "github.com/topfreegames/pitaya/v2/session/mocks" - "github.com/topfreegames/pitaya/v2/timer" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger/logrus" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/router" + "github.com/topfreegames/pitaya/v3/pkg/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/timer" ) var ( @@ -135,7 +135,7 @@ func TestGetServerByID(t *testing.T) { app := NewDefaultApp(true, "testtype", Cluster, map[string]string{}, *builderConfig) s, err := app.GetServerByID("id") assert.Nil(t, s) - assert.EqualError(t, constants.ErrNoServerWithID, err.Error()) + assert.EqualError(t, constants2.ErrNoServerWithID, err.Error()) } func TestGetServersByType(t *testing.T) { @@ -143,7 +143,7 @@ func TestGetServersByType(t *testing.T) { app := NewDefaultApp(true, "testtype", Cluster, map[string]string{}, *builderConfig) s, err := app.GetServersByType("id") assert.Nil(t, s) - assert.EqualError(t, constants.ErrNoServersAvailableOfType, err.Error()) + assert.EqualError(t, constants2.ErrNoServersAvailableOfType, err.Error()) } func TestSetHeartbeatInterval(t *testing.T) { @@ -172,29 +172,29 @@ func TestSetDictionary(t *testing.T) { app.running = true err = app.SetDictionary(dict) - assert.EqualError(t, constants.ErrChangeDictionaryWhileRunning, err.Error()) + assert.EqualError(t, constants2.ErrChangeDictionaryWhileRunning, err.Error()) } func TestAddRoute(t *testing.T) { builderConfig := config.NewDefaultBuilderConfig() app := NewDefaultApp(true, "testtype", Cluster, map[string]string{}, *builderConfig).(*App) app.router = nil - err := app.AddRoute("somesv", func(ctx context.Context, route *route.Route, payload []byte, servers map[string]*cluster.Server) (*cluster.Server, error) { + err := app.AddRoute("somesv", func(ctx context.Context, route *route.Route, payload []byte, servers map[string]*cluster2.Server) (*cluster2.Server, error) { return nil, nil }) - assert.EqualError(t, constants.ErrRouterNotInitialized, err.Error()) + assert.EqualError(t, constants2.ErrRouterNotInitialized, err.Error()) app.router = router.New() - err = app.AddRoute("somesv", func(ctx context.Context, route *route.Route, payload []byte, servers map[string]*cluster.Server) (*cluster.Server, error) { + err = app.AddRoute("somesv", func(ctx context.Context, route *route.Route, payload []byte, servers map[string]*cluster2.Server) (*cluster2.Server, error) { return nil, nil }) assert.NoError(t, err) app.running = true - err = app.AddRoute("somesv", func(ctx context.Context, route *route.Route, payload []byte, servers map[string]*cluster.Server) (*cluster.Server, error) { + err = app.AddRoute("somesv", func(ctx context.Context, route *route.Route, payload []byte, servers map[string]*cluster2.Server) (*cluster2.Server, error) { return nil, nil }) - assert.EqualError(t, constants.ErrChangeRouteWhileRunning, err.Error()) + assert.EqualError(t, constants2.ErrChangeRouteWhileRunning, err.Error()) } func TestShutdown(t *testing.T) { @@ -231,7 +231,7 @@ func TestDefaultSD(t *testing.T) { app := NewDefaultApp(true, "testtype", Cluster, map[string]string{}, *builderConfig).(*App) assert.NotNil(t, app.serviceDiscovery) - etcdSD, err := cluster.NewEtcdServiceDiscovery(*config.NewDefaultEtcdServiceDiscoveryConfig(), app.server, app.dieChan) + etcdSD, err := cluster2.NewEtcdServiceDiscovery(*config.NewDefaultEtcdServiceDiscoveryConfig(), app.server, app.dieChan) assert.NoError(t, err) typeOfetcdSD := reflect.TypeOf(etcdSD) @@ -247,7 +247,7 @@ func TestDefaultRPCServer(t *testing.T) { sessionPool := mocks.NewMockSessionPool(ctrl) - natsRPCServer, err := cluster.NewNatsRPCServer(*config.NewDefaultNatsRPCServerConfig(), app.server, nil, app.dieChan, sessionPool) + natsRPCServer, err := cluster2.NewNatsRPCServer(*config.NewDefaultNatsRPCServerConfig(), app.server, nil, app.dieChan, sessionPool) assert.NoError(t, err) typeOfNatsRPCServer := reflect.TypeOf(natsRPCServer) @@ -259,7 +259,7 @@ func TestDefaultRPCClient(t *testing.T) { app := NewDefaultApp(true, "testtype", Cluster, map[string]string{}, *builderConfig).(*App) assert.NotNil(t, app.rpcClient) - natsRPCClient, err := cluster.NewNatsRPCClient(*config.NewDefaultNatsRPCClientConfig(), app.server, nil, app.dieChan) + natsRPCClient, err := cluster2.NewNatsRPCClient(*config.NewDefaultNatsRPCClientConfig(), app.server, nil, app.dieChan) assert.NoError(t, err) typeOfNatsRPCClient := reflect.TypeOf(natsRPCClient) @@ -304,19 +304,19 @@ func TestStartAndListenCluster(t *testing.T) { var err error natsClientConfig := *config.NewDefaultNatsRPCClientConfig() natsClientConfig.Connect = fmt.Sprintf("nats://%s", nsAddr) - builder.RPCClient, err = cluster.NewNatsRPCClient(natsClientConfig, builder.Server, builder.MetricsReporters, builder.DieChan) + builder.RPCClient, err = cluster2.NewNatsRPCClient(natsClientConfig, builder.Server, builder.MetricsReporters, builder.DieChan) if err != nil { panic(err.Error()) } natsServerConfig := *config.NewDefaultNatsRPCServerConfig() natsServerConfig.Connect = fmt.Sprintf("nats://%s", nsAddr) - builder.RPCServer, err = cluster.NewNatsRPCServer(natsServerConfig, builder.Server, builder.MetricsReporters, builder.DieChan, builder.SessionPool) + builder.RPCServer, err = cluster2.NewNatsRPCServer(natsServerConfig, builder.Server, builder.MetricsReporters, builder.DieChan, builder.SessionPool) if err != nil { panic(err.Error()) } - etcdSD, err := cluster.NewEtcdServiceDiscovery(*config.NewDefaultEtcdServiceDiscoveryConfig(), builder.Server, builder.DieChan, cli) + etcdSD, err := cluster2.NewEtcdServiceDiscovery(*config.NewDefaultEtcdServiceDiscoveryConfig(), builder.Server, builder.DieChan, cli) builder.ServiceDiscovery = etcdSD assert.NoError(t, err) acc := acceptor.NewTCPAcceptor("0.0.0.0:0") @@ -376,7 +376,7 @@ func TestGetSessionFromCtx(t *testing.T) { ss := mocks.NewMockSession(ctrl) app := NewDefaultApp(true, "testtype", Cluster, map[string]string{}, *config.NewDefaultBuilderConfig()) - ctx := context.WithValue(context.Background(), constants.SessionCtxKey, ss) + ctx := context.WithValue(context.Background(), constants2.SessionCtxKey, ss) s := app.GetSessionFromCtx(ctx) assert.Equal(t, ss, s) } @@ -385,9 +385,9 @@ func TestAddMetricTagsToPropagateCtx(t *testing.T) { ctx := AddMetricTagsToPropagateCtx(context.Background(), map[string]string{ "key": "value", }) - val := ctx.Value(constants.PropagateCtxKey) + val := ctx.Value(constants2.PropagateCtxKey) assert.Equal(t, map[string]interface{}{ - constants.MetricTagsKey: map[string]string{ + constants2.MetricTagsKey: map[string]string{ "key": "value", }, }, val) @@ -395,7 +395,7 @@ func TestAddMetricTagsToPropagateCtx(t *testing.T) { func TestAddToPropagateCtx(t *testing.T) { ctx := AddToPropagateCtx(context.Background(), "key", "val") - val := ctx.Value(constants.PropagateCtxKey) + val := ctx.Value(constants2.PropagateCtxKey) assert.Equal(t, map[string]interface{}{"key": "val"}, val) } @@ -420,7 +420,7 @@ func TestDescriptor(t *testing.T) { bts, err = Descriptor("not_exists.proto") assert.Nil(t, bts) - assert.EqualError(t, constants.ErrProtodescriptor, err.Error()) + assert.EqualError(t, constants2.ErrProtodescriptor, err.Error()) } func TestDocumentation(t *testing.T) { @@ -568,14 +568,14 @@ func TestAddGRPCInfoToMetadata(t *testing.T) { metadata = AddGRPCInfoToMetadata(metadata, "region", "host", "port", "external-host", "external-port") assert.Equal(t, map[string]string{ - "key1": "value1", - "key2": "value2", - "key3": "value3", - constants.GRPCHostKey: "host", - constants.GRPCPortKey: "port", - constants.GRPCExternalHostKey: "external-host", - constants.GRPCExternalPortKey: "external-port", - constants.RegionKey: "region", + "key1": "value1", + "key2": "value2", + "key3": "value3", + constants2.GRPCHostKey: "host", + constants2.GRPCPortKey: "port", + constants2.GRPCExternalHostKey: "external-host", + constants2.GRPCExternalPortKey: "external-port", + constants2.RegionKey: "region", }, metadata) } @@ -606,6 +606,6 @@ func TestRegisterRPCJob(t *testing.T) { assert.NoError(t, err) err = app.RegisterRPCJob(nil) - assert.Equal(t, constants.ErrRPCJobAlreadyRegistered, err) + assert.Equal(t, constants2.ErrRPCJobAlreadyRegistered, err) }) } diff --git a/builder.go b/pkg/builder.go similarity index 64% rename from builder.go rename to pkg/builder.go index 96906673..1c0503db 100644 --- a/builder.go +++ b/pkg/builder.go @@ -1,44 +1,44 @@ -package pitaya +package pkg import ( "github.com/google/uuid" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/agent" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/conn/codec" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/defaultpipelines" - "github.com/topfreegames/pitaya/v2/groups" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/metrics/models" - "github.com/topfreegames/pitaya/v2/pipeline" - "github.com/topfreegames/pitaya/v2/router" - "github.com/topfreegames/pitaya/v2/serialize" - "github.com/topfreegames/pitaya/v2/serialize/json" - "github.com/topfreegames/pitaya/v2/service" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/worker" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + "github.com/topfreegames/pitaya/v3/pkg/agent" + cluster2 "github.com/topfreegames/pitaya/v3/pkg/cluster" + config2 "github.com/topfreegames/pitaya/v3/pkg/config" + codec2 "github.com/topfreegames/pitaya/v3/pkg/conn/codec" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/defaultpipelines" + groups2 "github.com/topfreegames/pitaya/v3/pkg/groups" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/metrics/models" + "github.com/topfreegames/pitaya/v3/pkg/pipeline" + "github.com/topfreegames/pitaya/v3/pkg/router" + "github.com/topfreegames/pitaya/v3/pkg/serialize" + "github.com/topfreegames/pitaya/v3/pkg/serialize/json" + "github.com/topfreegames/pitaya/v3/pkg/service" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/worker" ) // Builder holds dependency instances for a pitaya App type Builder struct { acceptors []acceptor.Acceptor - Config config.BuilderConfig + Config config2.BuilderConfig DieChan chan bool - PacketDecoder codec.PacketDecoder - PacketEncoder codec.PacketEncoder + PacketDecoder codec2.PacketDecoder + PacketEncoder codec2.PacketEncoder MessageEncoder *message.MessagesEncoder Serializer serialize.Serializer Router *router.Router - RPCClient cluster.RPCClient - RPCServer cluster.RPCServer + RPCClient cluster2.RPCClient + RPCServer cluster2.RPCServer MetricsReporters []metrics.Reporter - Server *cluster.Server + Server *cluster2.Server ServerMode ServerMode - ServiceDiscovery cluster.ServiceDiscovery - Groups groups.GroupService + ServiceDiscovery cluster2.ServiceDiscovery + Groups groups2.GroupService SessionPool session.SessionPool Worker *worker.Worker HandlerHooks *pipeline.HandlerHooks @@ -56,18 +56,18 @@ func NewBuilderWithConfigs( serverType string, serverMode ServerMode, serverMetadata map[string]string, - conf *config.Config, + conf *config2.Config, ) *Builder { - builderConfig := config.NewBuilderConfig(conf) - customMetrics := config.NewCustomMetricsSpec(conf) - prometheusConfig := config.NewPrometheusConfig(conf) - statsdConfig := config.NewStatsdConfig(conf) - etcdSDConfig := config.NewEtcdServiceDiscoveryConfig(conf) - natsRPCServerConfig := config.NewNatsRPCServerConfig(conf) - natsRPCClientConfig := config.NewNatsRPCClientConfig(conf) - workerConfig := config.NewWorkerConfig(conf) - enqueueOpts := config.NewEnqueueOpts(conf) - groupServiceConfig := config.NewMemoryGroupConfig(conf) + builderConfig := config2.NewBuilderConfig(conf) + customMetrics := config2.NewCustomMetricsSpec(conf) + prometheusConfig := config2.NewPrometheusConfig(conf) + statsdConfig := config2.NewStatsdConfig(conf) + etcdSDConfig := config2.NewEtcdServiceDiscoveryConfig(conf) + natsRPCServerConfig := config2.NewNatsRPCServerConfig(conf) + natsRPCClientConfig := config2.NewNatsRPCClientConfig(conf) + workerConfig := config2.NewWorkerConfig(conf) + enqueueOpts := config2.NewEnqueueOpts(conf) + groupServiceConfig := config2.NewMemoryGroupConfig(conf) return NewBuilder( isFrontend, serverType, @@ -88,16 +88,16 @@ func NewBuilderWithConfigs( // NewDefaultBuilder return a builder instance with default dependency instances for a pitaya App, // with default configs -func NewDefaultBuilder(isFrontend bool, serverType string, serverMode ServerMode, serverMetadata map[string]string, builderConfig config.BuilderConfig) *Builder { - customMetrics := config.NewDefaultCustomMetricsSpec() - prometheusConfig := config.NewDefaultPrometheusConfig() - statsdConfig := config.NewDefaultStatsdConfig() - etcdSDConfig := config.NewDefaultEtcdServiceDiscoveryConfig() - natsRPCServerConfig := config.NewDefaultNatsRPCServerConfig() - natsRPCClientConfig := config.NewDefaultNatsRPCClientConfig() - workerConfig := config.NewDefaultWorkerConfig() - enqueueOpts := config.NewDefaultEnqueueOpts() - groupServiceConfig := config.NewDefaultMemoryGroupConfig() +func NewDefaultBuilder(isFrontend bool, serverType string, serverMode ServerMode, serverMetadata map[string]string, builderConfig config2.BuilderConfig) *Builder { + customMetrics := config2.NewDefaultCustomMetricsSpec() + prometheusConfig := config2.NewDefaultPrometheusConfig() + statsdConfig := config2.NewDefaultStatsdConfig() + etcdSDConfig := config2.NewDefaultEtcdServiceDiscoveryConfig() + natsRPCServerConfig := config2.NewDefaultNatsRPCServerConfig() + natsRPCClientConfig := config2.NewDefaultNatsRPCClientConfig() + workerConfig := config2.NewDefaultWorkerConfig() + enqueueOpts := config2.NewDefaultEnqueueOpts() + groupServiceConfig := config2.NewDefaultMemoryGroupConfig() return NewBuilder( isFrontend, serverType, @@ -122,18 +122,18 @@ func NewBuilder(isFrontend bool, serverType string, serverMode ServerMode, serverMetadata map[string]string, - config config.BuilderConfig, + config config2.BuilderConfig, customMetrics models.CustomMetricsSpec, - prometheusConfig config.PrometheusConfig, - statsdConfig config.StatsdConfig, - etcdSDConfig config.EtcdServiceDiscoveryConfig, - natsRPCServerConfig config.NatsRPCServerConfig, - natsRPCClientConfig config.NatsRPCClientConfig, - workerConfig config.WorkerConfig, - enqueueOpts config.EnqueueOpts, - groupServiceConfig config.MemoryGroupConfig, + prometheusConfig config2.PrometheusConfig, + statsdConfig config2.StatsdConfig, + etcdSDConfig config2.EtcdServiceDiscoveryConfig, + natsRPCServerConfig config2.NatsRPCServerConfig, + natsRPCClientConfig config2.NatsRPCClientConfig, + workerConfig config2.WorkerConfig, + enqueueOpts config2.EnqueueOpts, + groupServiceConfig config2.MemoryGroupConfig, ) *Builder { - server := cluster.NewServer(uuid.New().String(), serverType, isFrontend, serverMetadata) + server := cluster2.NewServer(uuid.New().String(), serverType, isFrontend, serverMetadata) dieChan := make(chan bool) metricsReporters := []metrics.Reporter{} @@ -152,22 +152,22 @@ func NewBuilder(isFrontend bool, sessionPool := session.NewSessionPool() - var serviceDiscovery cluster.ServiceDiscovery - var rpcServer cluster.RPCServer - var rpcClient cluster.RPCClient + var serviceDiscovery cluster2.ServiceDiscovery + var rpcServer cluster2.RPCServer + var rpcClient cluster2.RPCClient if serverMode == Cluster { var err error - serviceDiscovery, err = cluster.NewEtcdServiceDiscovery(etcdSDConfig, server, dieChan) + serviceDiscovery, err = cluster2.NewEtcdServiceDiscovery(etcdSDConfig, server, dieChan) if err != nil { logger.Log.Fatalf("error creating default cluster service discovery component: %s", err.Error()) } - rpcServer, err = cluster.NewNatsRPCServer(natsRPCServerConfig, server, metricsReporters, dieChan, sessionPool) + rpcServer, err = cluster2.NewNatsRPCServer(natsRPCServerConfig, server, metricsReporters, dieChan, sessionPool) if err != nil { logger.Log.Fatalf("error setting default cluster rpc server component: %s", err.Error()) } - rpcClient, err = cluster.NewNatsRPCClient(natsRPCClientConfig, server, metricsReporters, dieChan) + rpcClient, err = cluster2.NewNatsRPCClient(natsRPCClientConfig, server, metricsReporters, dieChan) if err != nil { logger.Log.Fatalf("error setting default cluster rpc client component: %s", err.Error()) } @@ -178,7 +178,7 @@ func NewBuilder(isFrontend bool, logger.Log.Fatalf("error creating default worker: %s", err.Error()) } - gsi := groups.NewMemoryGroupService(groupServiceConfig) + gsi := groups2.NewMemoryGroupService(groupServiceConfig) if err != nil { panic(err) } @@ -187,8 +187,8 @@ func NewBuilder(isFrontend bool, acceptors: []acceptor.Acceptor{}, Config: config, DieChan: dieChan, - PacketDecoder: codec.NewPomeloPacketDecoder(), - PacketEncoder: codec.NewPomeloPacketEncoder(), + PacketDecoder: codec2.NewPomeloPacketDecoder(), + PacketEncoder: codec2.NewPomeloPacketEncoder(), MessageEncoder: message.NewMessagesEncoder(config.Pitaya.Handler.Messages.Compression), Serializer: json.NewSerializer(), Router: router.New(), @@ -291,7 +291,7 @@ func (builder *Builder) Build() Pitaya { } // NewDefaultApp returns a default pitaya app instance -func NewDefaultApp(isFrontend bool, serverType string, serverMode ServerMode, serverMetadata map[string]string, config config.BuilderConfig) Pitaya { +func NewDefaultApp(isFrontend bool, serverType string, serverMode ServerMode, serverMetadata map[string]string, config config2.BuilderConfig) Pitaya { builder := NewDefaultBuilder(isFrontend, serverType, serverMode, serverMetadata, config) return builder.Build() } @@ -300,7 +300,7 @@ func configureDefaultPipelines(handlerHooks *pipeline.HandlerHooks) { handlerHooks.BeforeHandler.PushBack(defaultpipelines.StructValidatorInstance.Validate) } -func addDefaultPrometheus(config config.PrometheusConfig, customMetrics models.CustomMetricsSpec, reporters []metrics.Reporter, serverType string) []metrics.Reporter { +func addDefaultPrometheus(config config2.PrometheusConfig, customMetrics models.CustomMetricsSpec, reporters []metrics.Reporter, serverType string) []metrics.Reporter { prometheus, err := CreatePrometheusReporter(serverType, config, customMetrics) if err != nil { logger.Log.Errorf("failed to start prometheus metrics reporter, skipping %v", err) @@ -310,7 +310,7 @@ func addDefaultPrometheus(config config.PrometheusConfig, customMetrics models.C return reporters } -func addDefaultStatsd(config config.StatsdConfig, reporters []metrics.Reporter, serverType string) []metrics.Reporter { +func addDefaultStatsd(config config2.StatsdConfig, reporters []metrics.Reporter, serverType string) []metrics.Reporter { statsd, err := CreateStatsdReporter(serverType, config) if err != nil { logger.Log.Errorf("failed to start statsd metrics reporter, skipping %v", err) diff --git a/client/client.go b/pkg/client/client.go similarity index 82% rename from client/client.go rename to pkg/client/client.go index 9fd6de78..9a4980b9 100644 --- a/client/client.go +++ b/pkg/client/client.go @@ -26,24 +26,23 @@ import ( "encoding/json" "errors" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + codec2 "github.com/topfreegames/pitaya/v3/pkg/conn/codec" + message2 "github.com/topfreegames/pitaya/v3/pkg/conn/message" + packet2 "github.com/topfreegames/pitaya/v3/pkg/conn/packet" "net" "net/url" "sync" "sync/atomic" "time" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/gorilla/websocket" "github.com/sirupsen/logrus" - "github.com/topfreegames/pitaya/v2" - "github.com/topfreegames/pitaya/v2/conn/codec" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/conn/packet" - "github.com/topfreegames/pitaya/v2/logger" - logruswrapper "github.com/topfreegames/pitaya/v2/logger/logrus" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/util/compression" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/pkg/logger" + logruswrapper "github.com/topfreegames/pitaya/v3/pkg/logger/logrus" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/util/compression" ) // HandshakeSys struct @@ -60,7 +59,7 @@ type HandshakeData struct { } type pendingRequest struct { - msg *message.Message + msg *message2.Message sentAt time.Time } @@ -68,22 +67,22 @@ type pendingRequest struct { type Client struct { conn net.Conn Connected bool - packetEncoder codec.PacketEncoder - packetDecoder codec.PacketDecoder - packetChan chan *packet.Packet - IncomingMsgChan chan *message.Message + packetEncoder codec2.PacketEncoder + packetDecoder codec2.PacketDecoder + packetChan chan *packet2.Packet + IncomingMsgChan chan *message2.Message pendingChan chan bool pendingRequests map[uint]*pendingRequest pendingReqMutex sync.Mutex requestTimeout time.Duration closeChan chan struct{} nextID uint32 - messageEncoder message.Encoder + messageEncoder message2.Encoder clientHandshakeData *session.HandshakeData } // MsgChannel return the incoming message channel -func (c *Client) MsgChannel() chan *message.Message { +func (c *Client) MsgChannel() chan *message2.Message { return c.IncomingMsgChan } @@ -107,15 +106,15 @@ func New(logLevel logrus.Level, requestTimeout ...time.Duration) *Client { return &Client{ Connected: false, - packetEncoder: codec.NewPomeloPacketEncoder(), - packetDecoder: codec.NewPomeloPacketDecoder(), - packetChan: make(chan *packet.Packet, 10), + packetEncoder: codec2.NewPomeloPacketEncoder(), + packetDecoder: codec2.NewPomeloPacketDecoder(), + packetChan: make(chan *packet2.Packet, 10), pendingRequests: make(map[uint]*pendingRequest), requestTimeout: reqTimeout, // 30 here is the limit of inflight messages // TODO this should probably be configurable pendingChan: make(chan bool, 30), - messageEncoder: message.NewMessagesEncoder(false), + messageEncoder: message2.NewMessagesEncoder(false), clientHandshakeData: &session.HandshakeData{ Sys: session.HandshakeClientData{ Platform: "mac", @@ -141,7 +140,7 @@ func (c *Client) sendHandshakeRequest() error { return err } - p, err := c.packetEncoder.Encode(packet.Handshake, enc) + p, err := c.packetEncoder.Encode(packet2.Handshake, enc) if err != nil { return err } @@ -158,7 +157,7 @@ func (c *Client) handleHandshakeResponse() error { } handshakePacket := packets[0] - if handshakePacket.Type != packet.Handshake { + if handshakePacket.Type != packet2.Handshake { return fmt.Errorf("got first packet from server that is not a handshake, aborting") } @@ -178,9 +177,9 @@ func (c *Client) handleHandshakeResponse() error { logger.Log.Debug("got handshake from sv, data: %v", handshake) if handshake.Sys.Dict != nil { - message.SetDictionary(handshake.Sys.Dict) + message2.SetDictionary(handshake.Sys.Dict) } - p, err := c.packetEncoder.Encode(packet.HandshakeAck, []byte{}) + p, err := c.packetEncoder.Encode(packet2.HandshakeAck, []byte{}) if err != nil { return err } @@ -217,8 +216,8 @@ func (c *Client) pendingRequestsReaper() { err := pitaya.Error(errors.New("request timeout"), "PIT-504") errMarshalled, _ := json.Marshal(err) // send a timeout to incoming msg chan - m := &message.Message{ - Type: message.Response, + m := &message2.Message{ + Type: message2.Response, ID: pendingReq.msg.ID, Route: pendingReq.msg.Route, Data: errMarshalled, @@ -240,14 +239,14 @@ func (c *Client) handlePackets() { select { case p := <-c.packetChan: switch p.Type { - case packet.Data: + case packet2.Data: //handle data logger.Log.Debug("got data: %s", string(p.Data)) - m, err := message.Decode(p.Data) + m, err := message2.Decode(p.Data) if err != nil { logger.Log.Errorf("error decoding msg from sv: %s", string(m.Data)) } - if m.Type == message.Response { + if m.Type == message2.Response { c.pendingReqMutex.Lock() if _, ok := c.pendingRequests[m.ID]; ok { delete(c.pendingRequests, m.ID) @@ -259,7 +258,7 @@ func (c *Client) handlePackets() { c.pendingReqMutex.Unlock() } c.IncomingMsgChan <- m - case packet.Kick: + case packet2.Kick: logger.Log.Warn("got kick packet from the server! disconnecting...") c.Disconnect() } @@ -269,7 +268,7 @@ func (c *Client) handlePackets() { } } -func (c *Client) readPackets(buf *bytes.Buffer) ([]*packet.Packet, error) { +func (c *Client) readPackets(buf *bytes.Buffer) ([]*packet2.Packet, error) { // listen for sv messages data := make([]byte, 1024) n := len(data) @@ -288,7 +287,7 @@ func (c *Client) readPackets(buf *bytes.Buffer) ([]*packet.Packet, error) { } totalProcessed := 0 for _, p := range packets { - totalProcessed += codec.HeadLength + p.Length + totalProcessed += codec2.HeadLength + p.Length } buf.Next(totalProcessed) @@ -320,7 +319,7 @@ func (c *Client) sendHeartbeats(interval int) { for { select { case <-t.C: - p, _ := c.packetEncoder.Encode(packet.Heartbeat, []byte{}) + p, _ := c.packetEncoder.Encode(packet2.Heartbeat, []byte{}) _, err := c.conn.Write(p) if err != nil { logger.Log.Errorf("error sending heartbeat to server: %s", err.Error()) @@ -355,7 +354,7 @@ func (c *Client) ConnectTo(addr string, tlsConfig ...*tls.Config) error { return err } c.conn = conn - c.IncomingMsgChan = make(chan *message.Message, 10) + c.IncomingMsgChan = make(chan *message2.Message, 10) if err = c.handleHandshake(); err != nil { return err @@ -386,7 +385,7 @@ func (c *Client) ConnectToWS(addr string, path string, tlsConfig ...*tls.Config) return err } - c.IncomingMsgChan = make(chan *message.Message, 10) + c.IncomingMsgChan = make(chan *message2.Message, 10) if err = c.handleHandshake(); err != nil { return err @@ -410,21 +409,21 @@ func (c *Client) handleHandshake() error { // SendRequest sends a request to the server func (c *Client) SendRequest(route string, data []byte) (uint, error) { - return c.sendMsg(message.Request, route, data) + return c.sendMsg(message2.Request, route, data) } // SendNotify sends a notify to the server func (c *Client) SendNotify(route string, data []byte) error { - _, err := c.sendMsg(message.Notify, route, data) + _, err := c.sendMsg(message2.Notify, route, data) return err } -func (c *Client) buildPacket(msg message.Message) ([]byte, error) { +func (c *Client) buildPacket(msg message2.Message) ([]byte, error) { encMsg, err := c.messageEncoder.Encode(&msg) if err != nil { return nil, err } - p, err := c.packetEncoder.Encode(packet.Data, encMsg) + p, err := c.packetEncoder.Encode(packet2.Data, encMsg) if err != nil { return nil, err } @@ -433,9 +432,9 @@ func (c *Client) buildPacket(msg message.Message) ([]byte, error) { } // sendMsg sends the request to the server -func (c *Client) sendMsg(msgType message.Type, route string, data []byte) (uint, error) { +func (c *Client) sendMsg(msgType message2.Type, route string, data []byte) (uint, error) { // TODO mount msg and encode - m := message.Message{ + m := message2.Message{ Type: msgType, ID: uint(atomic.AddUint32(&c.nextID, 1)), Route: route, @@ -443,7 +442,7 @@ func (c *Client) sendMsg(msgType message.Type, route string, data []byte) (uint, Err: false, } p, err := c.buildPacket(m) - if msgType == message.Request { + if msgType == message2.Request { c.pendingChan <- true c.pendingReqMutex.Lock() if _, ok := c.pendingRequests[m.ID]; !ok { diff --git a/client/client_test.go b/pkg/client/client_test.go similarity index 85% rename from client/client_test.go rename to pkg/client/client_test.go index 13388868..ef775d66 100644 --- a/client/client_test.go +++ b/pkg/client/client_test.go @@ -1,15 +1,15 @@ package client import ( + "github.com/topfreegames/pitaya/v3/pkg/conn/message" "testing" "time" "github.com/golang/mock/gomock" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/helpers" - "github.com/topfreegames/pitaya/v2/mocks" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/mocks" ) func TestSendRequestShouldTimeout(t *testing.T) { diff --git a/client/pitayaclient.go b/pkg/client/pitayaclient.go similarity index 93% rename from client/pitayaclient.go rename to pkg/client/pitayaclient.go index b8cb5487..6f524cc2 100644 --- a/client/pitayaclient.go +++ b/pkg/client/pitayaclient.go @@ -22,9 +22,9 @@ package client import ( "crypto/tls" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/session" + "github.com/topfreegames/pitaya/v3/pkg/session" ) // PitayaClient iface diff --git a/client/protoclient.go b/pkg/client/protoclient.go similarity index 98% rename from client/protoclient.go rename to pkg/client/protoclient.go index 048b142a..e2284dad 100644 --- a/client/protoclient.go +++ b/pkg/client/protoclient.go @@ -27,6 +27,7 @@ import ( "encoding/json" "errors" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" "io/ioutil" "strings" "time" @@ -36,9 +37,8 @@ import ( "github.com/jhump/protoreflect/desc" "github.com/jhump/protoreflect/dynamic" "github.com/sirupsen/logrus" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/protos" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/protos" ) // Command struct. Save the input and output type and proto descriptor for each diff --git a/cluster/cluster.go b/pkg/cluster/cluster.go similarity index 87% rename from cluster/cluster.go rename to pkg/cluster/cluster.go index 2b2a0d1a..5dbe9464 100644 --- a/cluster/cluster.go +++ b/pkg/cluster/cluster.go @@ -22,21 +22,22 @@ package cluster import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - pcontext "github.com/topfreegames/pitaya/v2/context" - "github.com/topfreegames/pitaya/v2/interfaces" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/tracing" + "github.com/topfreegames/pitaya/v3/pkg/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/tracing" ) // RPCServer interface type RPCServer interface { SetPitayaServer(protos.PitayaServer) + GetPitayaServer() protos.PitayaServer interfaces.Module } diff --git a/cluster/etcd_service_discovery.go b/pkg/cluster/etcd_service_discovery.go similarity index 99% rename from cluster/etcd_service_discovery.go rename to pkg/cluster/etcd_service_discovery.go index 206f2b60..e882c155 100644 --- a/cluster/etcd_service_discovery.go +++ b/pkg/cluster/etcd_service_discovery.go @@ -24,15 +24,15 @@ import ( "context" "encoding/json" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" + "github.com/topfreegames/pitaya/v3/pkg/util" + clientv3 "go.etcd.io/etcd/client/v3" + "go.etcd.io/etcd/client/v3/namespace" "strings" "sync" "time" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/util" - clientv3 "go.etcd.io/etcd/client/v3" - "go.etcd.io/etcd/client/v3/namespace" ) type etcdServiceDiscovery struct { diff --git a/cluster/etcd_service_discovery_test.go b/pkg/cluster/etcd_service_discovery_test.go similarity index 99% rename from cluster/etcd_service_discovery_test.go rename to pkg/cluster/etcd_service_discovery_test.go index 630efbe3..fbf2ba91 100644 --- a/cluster/etcd_service_discovery_test.go +++ b/pkg/cluster/etcd_service_discovery_test.go @@ -22,14 +22,14 @@ package cluster import ( "context" + "github.com/stretchr/testify/assert" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" + clientv3 "go.etcd.io/etcd/client/v3" "math" "testing" "time" - clientv3 "go.etcd.io/etcd/client/v3" - "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/helpers" ) var etcdSDTables = []struct { diff --git a/cluster/grpc_rpc_client.go b/pkg/cluster/grpc_rpc_client.go similarity index 84% rename from cluster/grpc_rpc_client.go rename to pkg/cluster/grpc_rpc_client.go index ea78e8cd..c6381421 100644 --- a/cluster/grpc_rpc_client.go +++ b/pkg/cluster/grpc_rpc_client.go @@ -23,22 +23,22 @@ package cluster import ( "context" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" + pitErrors "github.com/topfreegames/pitaya/v3/pkg/errors" "sync" "time" opentracing "github.com/opentracing/opentracing-go" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - pcontext "github.com/topfreegames/pitaya/v2/context" - pitErrors "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/interfaces" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/tracing" + "github.com/topfreegames/pitaya/v3/pkg/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/tracing" "google.golang.org/grpc" ) @@ -46,12 +46,12 @@ import ( type GRPCClient struct { bindingStorage interfaces.BindingStorage clientMap sync.Map - dialTimeout time.Duration - infoRetriever InfoRetriever - lazy bool + dialTimeout time.Duration + infoRetriever InfoRetriever + lazy bool metricsReporters []metrics.Reporter - reqTimeout time.Duration - server *Server + reqTimeout time.Duration + server *Server } // NewGRPCClient returns a new instance of GRPCClient @@ -100,7 +100,7 @@ func (gs *GRPCClient) Call( ) (*protos.Response, error) { c, ok := gs.clientMap.Load(server.ID) if !ok { - return nil, constants.ErrNoConnectionToServer + return nil, constants2.ErrNoConnectionToServer } parent, err := tracing.ExtractSpan(ctx) @@ -126,8 +126,8 @@ func (gs *GRPCClient) Call( if gs.metricsReporters != nil { startTime := time.Now() - ctxT = pcontext.AddToPropagateCtx(ctxT, constants.StartTimeKey, startTime.UnixNano()) - ctxT = pcontext.AddToPropagateCtx(ctxT, constants.RouteKey, route.String()) + ctxT = pcontext.AddToPropagateCtx(ctxT, constants2.StartTimeKey, startTime.UnixNano()) + ctxT = pcontext.AddToPropagateCtx(ctxT, constants2.RouteKey, route.String()) defer metrics.ReportTimingFromCtx(ctxT, gs.metricsReporters, "rpc", err) } @@ -151,13 +151,13 @@ func (gs *GRPCClient) Call( // Send not implemented in grpc client func (gs *GRPCClient) Send(uid string, d []byte) error { - return constants.ErrNotImplemented + return constants2.ErrNotImplemented } // BroadcastSessionBind sends the binding information to other servers that may be interested in this info func (gs *GRPCClient) BroadcastSessionBind(uid string) error { if gs.bindingStorage == nil { - return constants.ErrNoBindingStorageModule + return constants2.ErrNoBindingStorageModule } fid, _ := gs.bindingStorage.GetUserFrontendID(uid, gs.server.Type) if fid != "" { @@ -181,7 +181,7 @@ func (gs *GRPCClient) SendKick(userID string, serverType string, kick *protos.Ki var err error if gs.bindingStorage == nil { - return constants.ErrNoBindingStorageModule + return constants2.ErrNoBindingStorageModule } svID, err = gs.bindingStorage.GetUserFrontendID(userID, serverType) @@ -195,7 +195,7 @@ func (gs *GRPCClient) SendKick(userID string, serverType string, kick *protos.Ki err := c.(*grpcClient).sendKick(ctxT, kick) return err } - return constants.ErrNoConnectionToServer + return constants2.ErrNoConnectionToServer } // SendPush sends a message to an user, if you dont know the serverID that the user is connected to, you need to set a BindingStorage when creating the client @@ -207,7 +207,7 @@ func (gs *GRPCClient) SendPush(userID string, frontendSv *Server, push *protos.P svID = frontendSv.ID } else { if gs.bindingStorage == nil { - return constants.ErrNoBindingStorageModule + return constants2.ErrNoBindingStorageModule } svID, err = gs.bindingStorage.GetUserFrontendID(userID, frontendSv.Type) if err != nil { @@ -220,7 +220,7 @@ func (gs *GRPCClient) SendPush(userID string, frontendSv *Server, push *protos.P err := c.(*grpcClient).pushToUser(ctxT, push) return err } - return constants.ErrNoConnectionToServer + return constants2.ErrNoConnectionToServer } // AddServer is called when a new server is discovered @@ -272,9 +272,9 @@ func (gs *GRPCClient) Shutdown() error { func (gs *GRPCClient) getServerHost(sv *Server) (host, portKey string) { var ( - serverRegion, hasRegion = sv.Metadata[constants.RegionKey] - externalHost, hasExternal = sv.Metadata[constants.GRPCExternalHostKey] - internalHost, _ = sv.Metadata[constants.GRPCHostKey] + serverRegion, hasRegion = sv.Metadata[constants2.RegionKey] + externalHost, hasExternal = sv.Metadata[constants2.GRPCExternalHostKey] + internalHost, _ = sv.Metadata[constants2.GRPCHostKey] ) hasRegion = hasRegion && serverRegion != "" @@ -283,20 +283,20 @@ func (gs *GRPCClient) getServerHost(sv *Server) (host, portKey string) { if !hasRegion { if hasExternal { logger.Log.Warnf("[grpc client] server %s has no region specified in metadata, using external host", sv.ID) - return externalHost, constants.GRPCExternalPortKey + return externalHost, constants2.GRPCExternalPortKey } logger.Log.Warnf("[grpc client] server %s has no region nor external host specified in metadata, using internal host", sv.ID) - return internalHost, constants.GRPCPortKey + return internalHost, constants2.GRPCPortKey } if gs.infoRetriever.Region() == serverRegion || !hasExternal { logger.Log.Infof("[grpc client] server %s is in same region or external host not provided, using internal host", sv.ID) - return internalHost, constants.GRPCPortKey + return internalHost, constants2.GRPCPortKey } logger.Log.Infof("[grpc client] server %s is in other region, using external host", sv.ID) - return externalHost, constants.GRPCExternalPortKey + return externalHost, constants2.GRPCExternalPortKey } func (gc *grpcClient) connect() error { diff --git a/cluster/grpc_rpc_client_test.go b/pkg/cluster/grpc_rpc_client_test.go similarity index 88% rename from cluster/grpc_rpc_client_test.go rename to pkg/cluster/grpc_rpc_client_test.go index a721ad52..cefde57e 100644 --- a/cluster/grpc_rpc_client_test.go +++ b/pkg/cluster/grpc_rpc_client_test.go @@ -3,21 +3,21 @@ package cluster import ( "context" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/helpers" - "github.com/topfreegames/pitaya/v2/interfaces" - "github.com/topfreegames/pitaya/v2/interfaces/mocks" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/protos" - protosmocks "github.com/topfreegames/pitaya/v2/protos/mocks" - "github.com/topfreegames/pitaya/v2/route" - sessionmocks "github.com/topfreegames/pitaya/v2/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/interfaces/mocks" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/protos" + protosmocks "github.com/topfreegames/pitaya/v3/pkg/protos/mocks" + "github.com/topfreegames/pitaya/v3/pkg/route" + sessionmocks "github.com/topfreegames/pitaya/v3/pkg/session/mocks" "google.golang.org/grpc" ) @@ -91,7 +91,7 @@ func TestBroadcastSessionBind(t *testing.T) { name string bindingStorage interfaces.BindingStorage err error - }{{"shouldrun", mockBindingStorage, nil}, {"shoulderror", nil, constants.ErrNoBindingStorageModule}} + }{{"shouldrun", mockBindingStorage, nil}, {"shoulderror", nil, constants2.ErrNoBindingStorageModule}} for _, table := range tables { t.Run(table.name, func(t *testing.T) { @@ -146,7 +146,7 @@ func TestSendKick(t *testing.T) { {"nobindingstorage", "uid", nil, &Server{ Type: "tp", Frontend: true, - }, constants.ErrNoBindingStorageModule}, + }, constants2.ErrNoBindingStorageModule}, {"nobindingstorage", "", mockBindingStorage, &Server{ Type: "tp", Frontend: true, @@ -205,7 +205,7 @@ func TestSendPush(t *testing.T) { {"nobindingstorage-no-fid", nil, &Server{ Type: "tp", Frontend: true, - }, constants.ErrNoBindingStorageModule}, + }, constants2.ErrNoBindingStorageModule}, {"nobindingstorage-fid", nil, &Server{ ID: "someID", Type: "tp", @@ -273,8 +273,8 @@ func TestAddServer(t *testing.T) { ID: "someid", Type: "sometype", Metadata: map[string]string{ - constants.GRPCHostKey: "localhost", - constants.GRPCPortKey: fmt.Sprintf("%d", serverConfig.Port), + constants2.GRPCHostKey: "localhost", + constants2.GRPCPortKey: fmt.Sprintf("%d", serverConfig.Port), }, Frontend: false, } @@ -314,8 +314,8 @@ func TestAddServer(t *testing.T) { ID: "someid", Type: "sometype", Metadata: map[string]string{ - constants.GRPCHostKey: "localhost", - constants.GRPCPortKey: fmt.Sprintf("%d", serverConfig.Port), + constants2.GRPCHostKey: "localhost", + constants2.GRPCPortKey: fmt.Sprintf("%d", serverConfig.Port), }, Frontend: false, } @@ -358,35 +358,35 @@ func TestGetServerHost(t *testing.T) { }{ "test_has_no_region_and_no_external_host": { metadata: map[string]string{ - constants.GRPCHostKey: host, + constants2.GRPCHostKey: host, }, expectedHost: host, - expectedPortKey: constants.GRPCPortKey, + expectedPortKey: constants2.GRPCPortKey, }, "test_has_no_region_and_external_host": { metadata: map[string]string{ - constants.GRPCExternalHostKey: externalHost, + constants2.GRPCExternalHostKey: externalHost, }, expectedHost: externalHost, - expectedPortKey: constants.GRPCExternalPortKey, + expectedPortKey: constants2.GRPCExternalPortKey, }, "test_has_region_and_same_region": { metadata: map[string]string{ - constants.GRPCHostKey: host, - constants.RegionKey: region, + constants2.GRPCHostKey: host, + constants2.RegionKey: region, }, clientRegion: region, expectedHost: host, - expectedPortKey: constants.GRPCPortKey, + expectedPortKey: constants2.GRPCPortKey, }, "test_has_region_and_other_region": { metadata: map[string]string{ - constants.GRPCExternalHostKey: externalHost, - constants.RegionKey: region, + constants2.GRPCExternalHostKey: externalHost, + constants2.RegionKey: region, }, clientRegion: "other-region", expectedHost: externalHost, - expectedPortKey: constants.GRPCExternalPortKey, + expectedPortKey: constants2.GRPCExternalPortKey, }, } @@ -420,8 +420,8 @@ func TestRemoveServer(t *testing.T) { ID: "someid", Type: "sometype", Metadata: map[string]string{ - constants.GRPCHostKey: "localhost", - constants.GRPCPortKey: fmt.Sprintf("%d", serverConfig.Port), + constants2.GRPCHostKey: "localhost", + constants2.GRPCPortKey: fmt.Sprintf("%d", serverConfig.Port), }, Frontend: false, } diff --git a/cluster/grpc_rpc_server.go b/pkg/cluster/grpc_rpc_server.go similarity index 89% rename from cluster/grpc_rpc_server.go rename to pkg/cluster/grpc_rpc_server.go index 95a722c8..68862fac 100644 --- a/cluster/grpc_rpc_server.go +++ b/pkg/cluster/grpc_rpc_server.go @@ -22,13 +22,13 @@ package cluster import ( "fmt" + "github.com/topfreegames/pitaya/v3/pkg/config" "net" "google.golang.org/grpc" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/protos" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/protos" ) // GRPCServer rpc server struct @@ -63,6 +63,11 @@ func (gs *GRPCServer) Init() error { return nil } +// GetPitayaServer returns the currently set Pitaya Server +func (gs *GRPCServer) GetPitayaServer() protos.PitayaServer { + return gs.pitayaServer +} + // SetPitayaServer sets the pitaya server func (gs *GRPCServer) SetPitayaServer(ps protos.PitayaServer) { gs.pitayaServer = ps diff --git a/cluster/grpc_rpc_server_test.go b/pkg/cluster/grpc_rpc_server_test.go similarity index 76% rename from cluster/grpc_rpc_server_test.go rename to pkg/cluster/grpc_rpc_server_test.go index 556a0bd6..d51ba3b0 100644 --- a/cluster/grpc_rpc_server_test.go +++ b/pkg/cluster/grpc_rpc_server_test.go @@ -2,16 +2,16 @@ package cluster import ( "fmt" + "github.com/topfreegames/pitaya/v3/pkg/config" "net" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/helpers" - "github.com/topfreegames/pitaya/v2/metrics" - protosmocks "github.com/topfreegames/pitaya/v2/protos/mocks" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + protosmocks "github.com/topfreegames/pitaya/v3/pkg/protos/mocks" ) func TestNewGRPCServer(t *testing.T) { @@ -33,6 +33,9 @@ func TestGRPCServerInit(t *testing.T) { sv := getServer() gs, err := NewGRPCServer(*c, sv, []metrics.Reporter{}) gs.SetPitayaServer(mockPitayaServer) + + tSv := gs.GetPitayaServer() + assert.Equal(t, mockPitayaServer, tSv) err = gs.Init() assert.NoError(t, err) assert.NotNil(t, gs) diff --git a/cluster/info_retriever.go b/pkg/cluster/info_retriever.go similarity index 87% rename from cluster/info_retriever.go rename to pkg/cluster/info_retriever.go index 0875dca3..e42a2db0 100644 --- a/cluster/info_retriever.go +++ b/pkg/cluster/info_retriever.go @@ -1,6 +1,8 @@ package cluster -import "github.com/topfreegames/pitaya/v2/config" +import ( + "github.com/topfreegames/pitaya/v3/pkg/config" +) // infoRetriever gets cluster info from config // Implements InfoRetriever interface diff --git a/cluster/info_retriever_test.go b/pkg/cluster/info_retriever_test.go similarity index 63% rename from cluster/info_retriever_test.go rename to pkg/cluster/info_retriever_test.go index 90ce40e2..e7ba9d73 100644 --- a/cluster/info_retriever_test.go +++ b/pkg/cluster/info_retriever_test.go @@ -1,11 +1,11 @@ package cluster import ( + config2 "github.com/topfreegames/pitaya/v3/pkg/config" "testing" "github.com/spf13/viper" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/config" ) func TestInfoRetrieverRegion(t *testing.T) { @@ -13,9 +13,9 @@ func TestInfoRetrieverRegion(t *testing.T) { c := viper.New() c.Set("pitaya.cluster.info.region", "us") - conf := config.NewConfig(c) + conf := config2.NewConfig(c) - infoRetriever := NewInfoRetriever(*config.NewInfoRetrieverConfig(conf)) + infoRetriever := NewInfoRetriever(*config2.NewInfoRetrieverConfig(conf)) assert.Equal(t, "us", infoRetriever.Region()) } diff --git a/cluster/mocks/cluster.go b/pkg/cluster/mocks/cluster.go similarity index 79% rename from cluster/mocks/cluster.go rename to pkg/cluster/mocks/cluster.go index 03f524f2..a9cb3c04 100644 --- a/cluster/mocks/cluster.go +++ b/pkg/cluster/mocks/cluster.go @@ -1,7 +1,7 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: cluster/cluster.go +// Source: github.com/topfreegames/pitaya/v3/pkg/cluster (interfaces: RPCServer,RPCClient,SDListener,RemoteBindingListener,InfoRetriever) -// Package mock_cluster is a generated GoMock package. +// Package mocks is a generated GoMock package. package mocks import ( @@ -9,11 +9,11 @@ import ( reflect "reflect" gomock "github.com/golang/mock/gomock" - cluster "github.com/topfreegames/pitaya/v2/cluster" - message "github.com/topfreegames/pitaya/v2/conn/message" - protos "github.com/topfreegames/pitaya/v2/protos" - route "github.com/topfreegames/pitaya/v2/route" - session "github.com/topfreegames/pitaya/v2/session" + cluster "github.com/topfreegames/pitaya/v3/pkg/cluster" + message "github.com/topfreegames/pitaya/v3/pkg/conn/message" + protos "github.com/topfreegames/pitaya/v3/pkg/protos" + route "github.com/topfreegames/pitaya/v3/pkg/route" + session "github.com/topfreegames/pitaya/v3/pkg/session" ) // MockRPCServer is a mock of RPCServer interface. @@ -63,6 +63,20 @@ func (mr *MockRPCServerMockRecorder) BeforeShutdown() *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BeforeShutdown", reflect.TypeOf((*MockRPCServer)(nil).BeforeShutdown)) } +// GetPitayaServer mocks base method. +func (m *MockRPCServer) GetPitayaServer() protos.PitayaServer { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPitayaServer") + ret0, _ := ret[0].(protos.PitayaServer) + return ret0 +} + +// GetPitayaServer indicates an expected call of GetPitayaServer. +func (mr *MockRPCServerMockRecorder) GetPitayaServer() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPitayaServer", reflect.TypeOf((*MockRPCServer)(nil).GetPitayaServer)) +} + // Init mocks base method. func (m *MockRPCServer) Init() error { m.ctrl.T.Helper() @@ -151,32 +165,32 @@ func (mr *MockRPCClientMockRecorder) BeforeShutdown() *gomock.Call { } // BroadcastSessionBind mocks base method. -func (m *MockRPCClient) BroadcastSessionBind(uid string) error { +func (m *MockRPCClient) BroadcastSessionBind(arg0 string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BroadcastSessionBind", uid) + ret := m.ctrl.Call(m, "BroadcastSessionBind", arg0) ret0, _ := ret[0].(error) return ret0 } // BroadcastSessionBind indicates an expected call of BroadcastSessionBind. -func (mr *MockRPCClientMockRecorder) BroadcastSessionBind(uid interface{}) *gomock.Call { +func (mr *MockRPCClientMockRecorder) BroadcastSessionBind(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BroadcastSessionBind", reflect.TypeOf((*MockRPCClient)(nil).BroadcastSessionBind), uid) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BroadcastSessionBind", reflect.TypeOf((*MockRPCClient)(nil).BroadcastSessionBind), arg0) } // Call mocks base method. -func (m *MockRPCClient) Call(ctx context.Context, rpcType protos.RPCType, route *route.Route, session session.Session, msg *message.Message, server *cluster.Server) (*protos.Response, error) { +func (m *MockRPCClient) Call(arg0 context.Context, arg1 protos.RPCType, arg2 *route.Route, arg3 session.Session, arg4 *message.Message, arg5 *cluster.Server) (*protos.Response, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Call", ctx, rpcType, route, session, msg, server) + ret := m.ctrl.Call(m, "Call", arg0, arg1, arg2, arg3, arg4, arg5) ret0, _ := ret[0].(*protos.Response) ret1, _ := ret[1].(error) return ret0, ret1 } // Call indicates an expected call of Call. -func (mr *MockRPCClientMockRecorder) Call(ctx, rpcType, route, session, msg, server interface{}) *gomock.Call { +func (mr *MockRPCClientMockRecorder) Call(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Call", reflect.TypeOf((*MockRPCClient)(nil).Call), ctx, rpcType, route, session, msg, server) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Call", reflect.TypeOf((*MockRPCClient)(nil).Call), arg0, arg1, arg2, arg3, arg4, arg5) } // Init mocks base method. @@ -194,45 +208,45 @@ func (mr *MockRPCClientMockRecorder) Init() *gomock.Call { } // Send mocks base method. -func (m *MockRPCClient) Send(route string, data []byte) error { +func (m *MockRPCClient) Send(arg0 string, arg1 []byte) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Send", route, data) + ret := m.ctrl.Call(m, "Send", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // Send indicates an expected call of Send. -func (mr *MockRPCClientMockRecorder) Send(route, data interface{}) *gomock.Call { +func (mr *MockRPCClientMockRecorder) Send(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Send", reflect.TypeOf((*MockRPCClient)(nil).Send), route, data) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Send", reflect.TypeOf((*MockRPCClient)(nil).Send), arg0, arg1) } // SendKick mocks base method. -func (m *MockRPCClient) SendKick(userID, serverType string, kick *protos.KickMsg) error { +func (m *MockRPCClient) SendKick(arg0, arg1 string, arg2 *protos.KickMsg) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendKick", userID, serverType, kick) + ret := m.ctrl.Call(m, "SendKick", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // SendKick indicates an expected call of SendKick. -func (mr *MockRPCClientMockRecorder) SendKick(userID, serverType, kick interface{}) *gomock.Call { +func (mr *MockRPCClientMockRecorder) SendKick(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendKick", reflect.TypeOf((*MockRPCClient)(nil).SendKick), userID, serverType, kick) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendKick", reflect.TypeOf((*MockRPCClient)(nil).SendKick), arg0, arg1, arg2) } // SendPush mocks base method. -func (m *MockRPCClient) SendPush(userID string, frontendSv *cluster.Server, push *protos.Push) error { +func (m *MockRPCClient) SendPush(arg0 string, arg1 *cluster.Server, arg2 *protos.Push) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendPush", userID, frontendSv, push) + ret := m.ctrl.Call(m, "SendPush", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // SendPush indicates an expected call of SendPush. -func (mr *MockRPCClientMockRecorder) SendPush(userID, frontendSv, push interface{}) *gomock.Call { +func (mr *MockRPCClientMockRecorder) SendPush(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendPush", reflect.TypeOf((*MockRPCClient)(nil).SendPush), userID, frontendSv, push) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendPush", reflect.TypeOf((*MockRPCClient)(nil).SendPush), arg0, arg1, arg2) } // Shutdown mocks base method. @@ -320,15 +334,15 @@ func (m *MockRemoteBindingListener) EXPECT() *MockRemoteBindingListenerMockRecor } // OnUserBind mocks base method. -func (m *MockRemoteBindingListener) OnUserBind(uid, fid string) { +func (m *MockRemoteBindingListener) OnUserBind(arg0, arg1 string) { m.ctrl.T.Helper() - m.ctrl.Call(m, "OnUserBind", uid, fid) + m.ctrl.Call(m, "OnUserBind", arg0, arg1) } // OnUserBind indicates an expected call of OnUserBind. -func (mr *MockRemoteBindingListenerMockRecorder) OnUserBind(uid, fid interface{}) *gomock.Call { +func (mr *MockRemoteBindingListenerMockRecorder) OnUserBind(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnUserBind", reflect.TypeOf((*MockRemoteBindingListener)(nil).OnUserBind), uid, fid) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnUserBind", reflect.TypeOf((*MockRemoteBindingListener)(nil).OnUserBind), arg0, arg1) } // MockInfoRetriever is a mock of InfoRetriever interface. diff --git a/cluster/mocks/service_discovery.go b/pkg/cluster/mocks/service_discovery.go similarity index 91% rename from cluster/mocks/service_discovery.go rename to pkg/cluster/mocks/service_discovery.go index 60abcd6a..009dddf5 100644 --- a/cluster/mocks/service_discovery.go +++ b/pkg/cluster/mocks/service_discovery.go @@ -5,10 +5,10 @@ package mocks import ( + cluster2 "github.com/topfreegames/pitaya/v3/pkg/cluster" reflect "reflect" gomock "github.com/golang/mock/gomock" - cluster "github.com/topfreegames/pitaya/v2/cluster" ) // MockServiceDiscovery is a mock of ServiceDiscovery interface. @@ -35,7 +35,7 @@ func (m *MockServiceDiscovery) EXPECT() *MockServiceDiscoveryMockRecorder { } // AddListener mocks base method. -func (m *MockServiceDiscovery) AddListener(listener cluster.SDListener) { +func (m *MockServiceDiscovery) AddListener(listener cluster2.SDListener) { m.ctrl.T.Helper() m.ctrl.Call(m, "AddListener", listener) } @@ -71,10 +71,10 @@ func (mr *MockServiceDiscoveryMockRecorder) BeforeShutdown() *gomock.Call { } // GetServer mocks base method. -func (m *MockServiceDiscovery) GetServer(id string) (*cluster.Server, error) { +func (m *MockServiceDiscovery) GetServer(id string) (*cluster2.Server, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetServer", id) - ret0, _ := ret[0].(*cluster.Server) + ret0, _ := ret[0].(*cluster2.Server) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -86,10 +86,10 @@ func (mr *MockServiceDiscoveryMockRecorder) GetServer(id interface{}) *gomock.Ca } // GetServers mocks base method. -func (m *MockServiceDiscovery) GetServers() []*cluster.Server { +func (m *MockServiceDiscovery) GetServers() []*cluster2.Server { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetServers") - ret0, _ := ret[0].([]*cluster.Server) + ret0, _ := ret[0].([]*cluster2.Server) return ret0 } @@ -100,10 +100,10 @@ func (mr *MockServiceDiscoveryMockRecorder) GetServers() *gomock.Call { } // GetServersByType mocks base method. -func (m *MockServiceDiscovery) GetServersByType(serverType string) (map[string]*cluster.Server, error) { +func (m *MockServiceDiscovery) GetServersByType(serverType string) (map[string]*cluster2.Server, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetServersByType", serverType) - ret0, _ := ret[0].(map[string]*cluster.Server) + ret0, _ := ret[0].(map[string]*cluster2.Server) ret1, _ := ret[1].(error) return ret0, ret1 } diff --git a/cluster/nats_rpc_client.go b/pkg/cluster/nats_rpc_client.go similarity index 86% rename from cluster/nats_rpc_client.go rename to pkg/cluster/nats_rpc_client.go index 9a666f57..ce4071f8 100644 --- a/cluster/nats_rpc_client.go +++ b/pkg/cluster/nats_rpc_client.go @@ -23,22 +23,22 @@ package cluster import ( "context" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" + "github.com/topfreegames/pitaya/v3/pkg/errors" "time" "github.com/golang/protobuf/proto" nats "github.com/nats-io/nats.go" opentracing "github.com/opentracing/opentracing-go" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - pcontext "github.com/topfreegames/pitaya/v2/context" - "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/tracing" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/tracing" ) // NatsRPCClient struct @@ -77,13 +77,13 @@ func NewNatsRPCClient( func (ns *NatsRPCClient) configure(config config.NatsRPCClientConfig) error { ns.connString = config.Connect if ns.connString == "" { - return constants.ErrNoNatsConnectionString + return constants2.ErrNoNatsConnectionString } ns.connectionTimeout = config.ConnectionTimeout ns.maxReconnectionRetries = config.MaxReconnectionRetries ns.reqTimeout = config.RequestTimeout if ns.reqTimeout == 0 { - return constants.ErrNatsNoRequestTimeout + return constants2.ErrNatsNoRequestTimeout } return nil } @@ -104,7 +104,7 @@ func (ns *NatsRPCClient) BroadcastSessionBind(uid string) error { // Send publishes a message in a given topic func (ns *NatsRPCClient) Send(topic string, data []byte) error { if !ns.running { - return constants.ErrRPCClientNotInitialized + return constants2.ErrRPCClientNotInitialized } return ns.conn.Publish(topic, data) } @@ -152,7 +152,7 @@ func (ns *NatsRPCClient) Call( defer tracing.FinishSpan(ctx, err) if !ns.running { - err = constants.ErrRPCClientNotInitialized + err = constants2.ErrRPCClientNotInitialized return nil, err } req, err := buildRequest(ctx, rpcType, route, session, msg, ns.server) @@ -168,8 +168,8 @@ func (ns *NatsRPCClient) Call( if ns.metricsReporters != nil { startTime := time.Now() - ctx = pcontext.AddToPropagateCtx(ctx, constants.StartTimeKey, startTime.UnixNano()) - ctx = pcontext.AddToPropagateCtx(ctx, constants.RouteKey, route.String()) + ctx = pcontext.AddToPropagateCtx(ctx, constants2.StartTimeKey, startTime.UnixNano()) + ctx = pcontext.AddToPropagateCtx(ctx, constants2.RouteKey, route.String()) defer func() { typ := "rpc" metrics.ReportTimingFromCtx(ctx, ns.metricsReporters, typ, err) diff --git a/cluster/nats_rpc_client_test.go b/pkg/cluster/nats_rpc_client_test.go similarity index 95% rename from cluster/nats_rpc_client_test.go rename to pkg/cluster/nats_rpc_client_test.go index c1b017e7..d60e0d9d 100644 --- a/cluster/nats_rpc_client_test.go +++ b/pkg/cluster/nats_rpc_client_test.go @@ -24,6 +24,10 @@ import ( "context" "errors" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/constants" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "testing" "time" @@ -32,16 +36,12 @@ import ( "github.com/google/uuid" nats "github.com/nats-io/nats.go" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/helpers" - "github.com/topfreegames/pitaya/v2/metrics" - metricsmocks "github.com/topfreegames/pitaya/v2/metrics/mocks" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/route" - sessionmocks "github.com/topfreegames/pitaya/v2/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + metricsmocks "github.com/topfreegames/pitaya/v3/pkg/metrics/mocks" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" + sessionmocks "github.com/topfreegames/pitaya/v3/pkg/session/mocks" ) func TestNewNatsRPCClient(t *testing.T) { @@ -469,7 +469,7 @@ func TestNatsRPCClientCall(t *testing.T) { ss.EXPECT().GetDataEncoded().Return(data2).Times(1) res, err := rpcClient.Call(context.Background(), protos.RPCType_Sys, rt, ss, msg, sv2) - assert.Equal(t, table.expected, res) + assert.True(t, proto.Equal(table.expected, res)) if table.err != nil { assert.Error(t, err) assert.Contains(t, err.Error(), table.err.Error()) diff --git a/cluster/nats_rpc_common.go b/pkg/cluster/nats_rpc_common.go similarity index 97% rename from cluster/nats_rpc_common.go rename to pkg/cluster/nats_rpc_common.go index 8396aadd..d45c5971 100644 --- a/cluster/nats_rpc_common.go +++ b/pkg/cluster/nats_rpc_common.go @@ -24,7 +24,7 @@ import ( "fmt" nats "github.com/nats-io/nats.go" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) func getChannel(serverType, serverID string) string { diff --git a/cluster/nats_rpc_common_test.go b/pkg/cluster/nats_rpc_common_test.go similarity index 97% rename from cluster/nats_rpc_common_test.go rename to pkg/cluster/nats_rpc_common_test.go index e404703e..da7eeba2 100644 --- a/cluster/nats_rpc_common_test.go +++ b/pkg/cluster/nats_rpc_common_test.go @@ -27,7 +27,7 @@ import ( nats "github.com/nats-io/nats.go" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/helpers" + "github.com/topfreegames/pitaya/v3/pkg/helpers" ) func getServer() *Server { diff --git a/cluster/nats_rpc_server.go b/pkg/cluster/nats_rpc_server.go similarity index 95% rename from cluster/nats_rpc_server.go rename to pkg/cluster/nats_rpc_server.go index 4aa51341..da690003 100644 --- a/cluster/nats_rpc_server.go +++ b/pkg/cluster/nats_rpc_server.go @@ -24,19 +24,19 @@ import ( "context" "errors" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "math" "time" "github.com/golang/protobuf/proto" nats "github.com/nats-io/nats.go" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/util" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/util" ) // NatsRPCServer struct @@ -122,6 +122,11 @@ func (ns *NatsRPCServer) GetBindingsChannel() chan *nats.Msg { return ns.bindingsChan } +// GetPitayaServer returns the currently set Pitaya Server +func (ns *NatsRPCServer) GetPitayaServer() protos.PitayaServer { + return ns.pitayaServer +} + // GetUserMessagesTopic get the topic for user func GetUserMessagesTopic(uid string, svType string) string { return fmt.Sprintf("pitaya/%s/user/%s/push", svType, uid) diff --git a/cluster/nats_rpc_server_test.go b/pkg/cluster/nats_rpc_server_test.go similarity index 96% rename from cluster/nats_rpc_server_test.go rename to pkg/cluster/nats_rpc_server_test.go index a2d84768..f8f4b289 100644 --- a/cluster/nats_rpc_server_test.go +++ b/pkg/cluster/nats_rpc_server_test.go @@ -23,6 +23,8 @@ package cluster import ( "context" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" "reflect" "testing" "time" @@ -31,14 +33,12 @@ import ( "github.com/golang/protobuf/proto" nats "github.com/nats-io/nats.go" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/helpers" - "github.com/topfreegames/pitaya/v2/metrics" - metricsmocks "github.com/topfreegames/pitaya/v2/metrics/mocks" - "github.com/topfreegames/pitaya/v2/protos" - protosmocks "github.com/topfreegames/pitaya/v2/protos/mocks" - sessionmocks "github.com/topfreegames/pitaya/v2/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + metricsmocks "github.com/topfreegames/pitaya/v3/pkg/metrics/mocks" + "github.com/topfreegames/pitaya/v3/pkg/protos" + protosmocks "github.com/topfreegames/pitaya/v3/pkg/protos/mocks" + sessionmocks "github.com/topfreegames/pitaya/v3/pkg/session/mocks" ) type funcPtrMatcher struct { @@ -396,6 +396,9 @@ func TestNatsRPCServerProcessBindings(t *testing.T) { defer ctrl.Finish() rpcServer.SetPitayaServer(pitayaSvMock) + // test GetPitayaServer just to get test coverage ( why not? (: ) + tSv := rpcServer.GetPitayaServer() + assert.Equal(t, pitayaSvMock, tSv) bindMsg := &protos.BindMsg{ Uid: "testuid", diff --git a/cluster/server.go b/pkg/cluster/server.go similarity index 97% rename from cluster/server.go rename to pkg/cluster/server.go index 95bfe879..85ad5ad8 100644 --- a/cluster/server.go +++ b/pkg/cluster/server.go @@ -24,7 +24,7 @@ import ( "encoding/json" "os" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) // Server struct diff --git a/cluster/server_test.go b/pkg/cluster/server_test.go similarity index 100% rename from cluster/server_test.go rename to pkg/cluster/server_test.go diff --git a/cluster/service_discovery.go b/pkg/cluster/service_discovery.go similarity index 96% rename from cluster/service_discovery.go rename to pkg/cluster/service_discovery.go index ef4871a2..f2dbe142 100644 --- a/cluster/service_discovery.go +++ b/pkg/cluster/service_discovery.go @@ -20,7 +20,7 @@ package cluster -import "github.com/topfreegames/pitaya/v2/interfaces" +import "github.com/topfreegames/pitaya/v3/pkg/interfaces" // ServiceDiscovery is the interface for a service discovery client type ServiceDiscovery interface { diff --git a/component.go b/pkg/component.go similarity index 89% rename from component.go rename to pkg/component.go index 647f0ef6..351d3bd9 100644 --- a/component.go +++ b/pkg/component.go @@ -18,25 +18,25 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" ) type regComp struct { - comp component.Component - opts []component.Option + comp component2.Component + opts []component2.Option } // Register register a component with options -func (app *App) Register(c component.Component, options ...component.Option) { +func (app *App) Register(c component2.Component, options ...component2.Option) { app.handlerComp = append(app.handlerComp, regComp{c, options}) } // RegisterRemote register a remote component with options -func (app *App) RegisterRemote(c component.Component, options ...component.Option) { +func (app *App) RegisterRemote(c component2.Component, options ...component2.Option) { app.remoteComp = append(app.remoteComp, regComp{c, options}) } diff --git a/component/base.go b/pkg/component/base.go similarity index 100% rename from component/base.go rename to pkg/component/base.go diff --git a/component/component.go b/pkg/component/component.go similarity index 100% rename from component/component.go rename to pkg/component/component.go diff --git a/component/method.go b/pkg/component/method.go similarity index 98% rename from component/method.go rename to pkg/component/method.go index 2d157c3e..619ac5cd 100644 --- a/component/method.go +++ b/pkg/component/method.go @@ -22,12 +22,12 @@ package component import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" "reflect" "unicode" "unicode/utf8" "github.com/golang/protobuf/proto" - "github.com/topfreegames/pitaya/v2/conn/message" ) var ( diff --git a/component/method_test.go b/pkg/component/method_test.go similarity index 98% rename from component/method_test.go rename to pkg/component/method_test.go index 2f67dfa2..816d6f3c 100644 --- a/component/method_test.go +++ b/pkg/component/method_test.go @@ -27,7 +27,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/protos/test" + "github.com/topfreegames/pitaya/v3/pkg/protos/test" ) type TestType struct { diff --git a/component/options.go b/pkg/component/options.go similarity index 100% rename from component/options.go rename to pkg/component/options.go diff --git a/component/options_test.go b/pkg/component/options_test.go similarity index 100% rename from component/options_test.go rename to pkg/component/options_test.go diff --git a/component/service.go b/pkg/component/service.go similarity index 98% rename from component/service.go rename to pkg/component/service.go index 383f9603..28e84ab9 100644 --- a/component/service.go +++ b/pkg/component/service.go @@ -22,10 +22,9 @@ package component import ( "errors" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/constants" "reflect" - - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" ) type ( diff --git a/component/service_test.go b/pkg/component/service_test.go similarity index 96% rename from component/service_test.go rename to pkg/component/service_test.go index ca2cbe47..2f60f254 100644 --- a/component/service_test.go +++ b/pkg/component/service_test.go @@ -22,11 +22,11 @@ package component import ( "errors" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" ) type unexportedTestType struct { @@ -38,9 +38,9 @@ type ExportedTypeWithNoHandlerAndNoRemote struct { } var tables = []struct { - name string - comp Component - err error + name string + comp Component + err error handlers []string remotes []string }{ diff --git a/component_test.go b/pkg/component_test.go similarity index 96% rename from component_test.go rename to pkg/component_test.go index 056f92e8..f65439b1 100644 --- a/component_test.go +++ b/pkg/component_test.go @@ -18,14 +18,14 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( + "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/config" "testing" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" ) type MyComp struct { diff --git a/config/config.go b/pkg/config/config.go similarity index 97% rename from config/config.go rename to pkg/config/config.go index a569e5ef..c22b0b4a 100644 --- a/config/config.go +++ b/pkg/config/config.go @@ -2,9 +2,12 @@ package config import ( "fmt" + "os" + "path/filepath" + "strings" "time" - "github.com/topfreegames/pitaya/v2/metrics/models" + "github.com/topfreegames/pitaya/v3/pkg/metrics/models" ) // PitayaConfig provides configuration for a pitaya app @@ -176,6 +179,21 @@ func NewBuilderConfig(config *Config) *BuilderConfig { return conf } +type SidecarConfig struct { + CallTimeout time.Duration + Bind string + BindProtocol string +} + +func NewDefaultSidecarConfig() *SidecarConfig { + tmpDir := os.TempDir() + return &SidecarConfig{ + CallTimeout: 1 * time.Second, + Bind: filepath.FromSlash(fmt.Sprintf("%s/pitaya.sock", strings.TrimSuffix(tmpDir, "/"))), + BindProtocol: "unix", + } +} + // GRPCClientConfig rpc client config struct type GRPCClientConfig struct { DialTimeout time.Duration diff --git a/config/config_test.go b/pkg/config/config_test.go similarity index 100% rename from config/config_test.go rename to pkg/config/config_test.go diff --git a/config/viper_config.go b/pkg/config/viper_config.go similarity index 100% rename from config/viper_config.go rename to pkg/config/viper_config.go diff --git a/conn/codec/constants.go b/pkg/conn/codec/constants.go similarity index 100% rename from conn/codec/constants.go rename to pkg/conn/codec/constants.go diff --git a/conn/codec/mocks/packet_decoder.go b/pkg/conn/codec/mocks/packet_decoder.go similarity index 96% rename from conn/codec/mocks/packet_decoder.go rename to pkg/conn/codec/mocks/packet_decoder.go index 83a88d40..88c8cd2f 100644 --- a/conn/codec/mocks/packet_decoder.go +++ b/pkg/conn/codec/mocks/packet_decoder.go @@ -6,7 +6,7 @@ package mocks import ( gomock "github.com/golang/mock/gomock" - packet "github.com/topfreegames/pitaya/v2/conn/packet" + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" reflect "reflect" ) diff --git a/conn/codec/mocks/packet_encoder.go b/pkg/conn/codec/mocks/packet_encoder.go similarity index 96% rename from conn/codec/mocks/packet_encoder.go rename to pkg/conn/codec/mocks/packet_encoder.go index a5921f87..0ed35a7c 100644 --- a/conn/codec/mocks/packet_encoder.go +++ b/pkg/conn/codec/mocks/packet_encoder.go @@ -6,7 +6,7 @@ package mocks import ( gomock "github.com/golang/mock/gomock" - packet "github.com/topfreegames/pitaya/v2/conn/packet" + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" reflect "reflect" ) diff --git a/conn/codec/packet_decoder.go b/pkg/conn/codec/packet_decoder.go similarity index 95% rename from conn/codec/packet_decoder.go rename to pkg/conn/codec/packet_decoder.go index 9f85a60f..e176935c 100644 --- a/conn/codec/packet_decoder.go +++ b/pkg/conn/codec/packet_decoder.go @@ -20,7 +20,9 @@ package codec -import "github.com/topfreegames/pitaya/v2/conn/packet" +import ( + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" +) // PacketDecoder interface type PacketDecoder interface { diff --git a/conn/codec/packet_encoder.go b/pkg/conn/codec/packet_encoder.go similarity index 95% rename from conn/codec/packet_encoder.go rename to pkg/conn/codec/packet_encoder.go index e2158195..0b49a7ed 100644 --- a/conn/codec/packet_encoder.go +++ b/pkg/conn/codec/packet_encoder.go @@ -20,7 +20,9 @@ package codec -import "github.com/topfreegames/pitaya/v2/conn/packet" +import ( + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" +) // PacketEncoder interface type PacketEncoder interface { diff --git a/conn/codec/pomelo_packet_decoder.go b/pkg/conn/codec/pomelo_packet_decoder.go similarity index 89% rename from conn/codec/pomelo_packet_decoder.go rename to pkg/conn/codec/pomelo_packet_decoder.go index 28378a8c..a199850b 100644 --- a/conn/codec/pomelo_packet_decoder.go +++ b/pkg/conn/codec/pomelo_packet_decoder.go @@ -22,8 +22,7 @@ package codec import ( "bytes" - - "github.com/topfreegames/pitaya/v2/conn/packet" + packet2 "github.com/topfreegames/pitaya/v3/pkg/conn/packet" ) // PomeloPacketDecoder reads and decodes network data slice following pomelo's protocol @@ -34,18 +33,18 @@ func NewPomeloPacketDecoder() *PomeloPacketDecoder { return &PomeloPacketDecoder{} } -func (c *PomeloPacketDecoder) forward(buf *bytes.Buffer) (int, packet.Type, error) { +func (c *PomeloPacketDecoder) forward(buf *bytes.Buffer) (int, packet2.Type, error) { header := buf.Next(HeadLength) return ParseHeader(header) } // Decode decode the network bytes slice to packet.Packet(s) -func (c *PomeloPacketDecoder) Decode(data []byte) ([]*packet.Packet, error) { +func (c *PomeloPacketDecoder) Decode(data []byte) ([]*packet2.Packet, error) { buf := bytes.NewBuffer(nil) buf.Write(data) var ( - packets []*packet.Packet + packets []*packet2.Packet err error ) // check length @@ -60,7 +59,7 @@ func (c *PomeloPacketDecoder) Decode(data []byte) ([]*packet.Packet, error) { } for size <= buf.Len() { - p := &packet.Packet{Type: typ, Length: size, Data: buf.Next(size)} + p := &packet2.Packet{Type: typ, Length: size, Data: buf.Next(size)} packets = append(packets, p) // if no more packets, break diff --git a/conn/codec/pomelo_packet_decoder_test.go b/pkg/conn/codec/pomelo_packet_decoder_test.go similarity index 56% rename from conn/codec/pomelo_packet_decoder_test.go rename to pkg/conn/codec/pomelo_packet_decoder_test.go index 7d3d8771..421fc0e0 100644 --- a/conn/codec/pomelo_packet_decoder_test.go +++ b/pkg/conn/codec/pomelo_packet_decoder_test.go @@ -2,39 +2,39 @@ package codec import ( "bytes" + packet2 "github.com/topfreegames/pitaya/v3/pkg/conn/packet" "testing" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/conn/packet" ) var forwardTables = map[string]struct { buf []byte err error }{ - "test_handshake_type": {[]byte{packet.Handshake, 0x00, 0x00, 0x00}, nil}, - "test_handshake_ack_type": {[]byte{packet.HandshakeAck, 0x00, 0x00, 0x00}, nil}, - "test_heartbeat_type": {[]byte{packet.Heartbeat, 0x00, 0x00, 0x00}, nil}, - "test_data_type": {[]byte{packet.Data, 0x00, 0x00, 0x00}, nil}, - "test_kick_type": {[]byte{packet.Kick, 0x00, 0x00, 0x00}, nil}, + "test_handshake_type": {[]byte{packet2.Handshake, 0x00, 0x00, 0x00}, nil}, + "test_handshake_ack_type": {[]byte{packet2.HandshakeAck, 0x00, 0x00, 0x00}, nil}, + "test_heartbeat_type": {[]byte{packet2.Heartbeat, 0x00, 0x00, 0x00}, nil}, + "test_data_type": {[]byte{packet2.Data, 0x00, 0x00, 0x00}, nil}, + "test_kick_type": {[]byte{packet2.Kick, 0x00, 0x00, 0x00}, nil}, - "test_wrong_packet_type": {[]byte{0x06, 0x00, 0x00, 0x00}, packet.ErrWrongPomeloPacketType}, + "test_wrong_packet_type": {[]byte{0x06, 0x00, 0x00, 0x00}, packet2.ErrWrongPomeloPacketType}, } var ( - handshakeHeaderPacket = []byte{packet.Handshake, 0x00, 0x00, 0x01, 0x01} + handshakeHeaderPacket = []byte{packet2.Handshake, 0x00, 0x00, 0x01, 0x01} invalidHeader = []byte{0xff, 0x00, 0x00, 0x01} ) var decodeTables = map[string]struct { data []byte - packet []*packet.Packet + packet []*packet2.Packet err error }{ "test_not_enough_bytes": {[]byte{0x01}, nil, nil}, - "test_error_on_forward": {invalidHeader, nil, packet.ErrWrongPomeloPacketType}, - "test_forward": {handshakeHeaderPacket, []*packet.Packet{{packet.Handshake, 1, []byte{0x01}}}, nil}, - "test_forward_many": {append(handshakeHeaderPacket, handshakeHeaderPacket...), []*packet.Packet{{packet.Handshake, 1, []byte{0x01}}, {packet.Handshake, 1, []byte{0x01}}}, nil}, + "test_error_on_forward": {invalidHeader, nil, packet2.ErrWrongPomeloPacketType}, + "test_forward": {handshakeHeaderPacket, []*packet2.Packet{{packet2.Handshake, 1, []byte{0x01}}}, nil}, + "test_forward_many": {append(handshakeHeaderPacket, handshakeHeaderPacket...), []*packet2.Packet{{packet2.Handshake, 1, []byte{0x01}}, {packet2.Handshake, 1, []byte{0x01}}}, nil}, } func TestNewPomeloPacketDecoder(t *testing.T) { @@ -54,7 +54,7 @@ func TestForward(t *testing.T) { sz, typ, err := ppd.forward(bytes.NewBuffer(table.buf)) if table.err == nil { - assert.Equal(t, packet.Type(table.buf[0]), typ) + assert.Equal(t, packet2.Type(table.buf[0]), typ) assert.Equal(t, 0, sz) } diff --git a/conn/codec/pomelo_packet_encoder.go b/pkg/conn/codec/pomelo_packet_encoder.go similarity index 86% rename from conn/codec/pomelo_packet_encoder.go rename to pkg/conn/codec/pomelo_packet_encoder.go index 2551a7c7..1afa60a2 100644 --- a/conn/codec/pomelo_packet_encoder.go +++ b/pkg/conn/codec/pomelo_packet_encoder.go @@ -21,7 +21,7 @@ package codec import ( - "github.com/topfreegames/pitaya/v2/conn/packet" + packet2 "github.com/topfreegames/pitaya/v3/pkg/conn/packet" ) // PomeloPacketEncoder struct @@ -39,16 +39,16 @@ func NewPomeloPacketEncoder() *PomeloPacketEncoder { // --|----------------|-- // --------|------------------------|-------- // 1 byte packet type, 3 bytes packet data length(big end), and data segment -func (e *PomeloPacketEncoder) Encode(typ packet.Type, data []byte) ([]byte, error) { - if typ < packet.Handshake || typ > packet.Kick { - return nil, packet.ErrWrongPomeloPacketType +func (e *PomeloPacketEncoder) Encode(typ packet2.Type, data []byte) ([]byte, error) { + if typ < packet2.Handshake || typ > packet2.Kick { + return nil, packet2.ErrWrongPomeloPacketType } if len(data) > MaxPacketSize { return nil, ErrPacketSizeExcced } - p := &packet.Packet{Type: typ, Length: len(data)} + p := &packet2.Packet{Type: typ, Length: len(data)} buf := make([]byte, p.Length+HeadLength) buf[0] = byte(p.Type) diff --git a/conn/codec/pomelo_packet_encoder_test.go b/pkg/conn/codec/pomelo_packet_encoder_test.go similarity index 95% rename from conn/codec/pomelo_packet_encoder_test.go rename to pkg/conn/codec/pomelo_packet_encoder_test.go index 8098ba92..772fa604 100644 --- a/conn/codec/pomelo_packet_encoder_test.go +++ b/pkg/conn/codec/pomelo_packet_encoder_test.go @@ -1,10 +1,10 @@ package codec import ( + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" "testing" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/conn/packet" ) func helperConcatBytes(packetType packet.Type, length, data []byte) []byte { diff --git a/conn/codec/utils.go b/pkg/conn/codec/utils.go similarity index 93% rename from conn/codec/utils.go rename to pkg/conn/codec/utils.go index fe3f3cbc..b044d073 100644 --- a/conn/codec/utils.go +++ b/pkg/conn/codec/utils.go @@ -1,6 +1,8 @@ package codec -import "github.com/topfreegames/pitaya/v2/conn/packet" +import ( + "github.com/topfreegames/pitaya/v3/pkg/conn/packet" +) // ParseHeader parses a packet header and returns its dataLen and packetType or an error func ParseHeader(header []byte) (int, packet.Type, error) { diff --git a/conn/message/fixtures/test_invalid_message.golden b/pkg/conn/message/fixtures/test_invalid_message.golden similarity index 100% rename from conn/message/fixtures/test_invalid_message.golden rename to pkg/conn/message/fixtures/test_invalid_message.golden diff --git a/conn/message/fixtures/test_must_gzip.golden b/pkg/conn/message/fixtures/test_must_gzip.golden similarity index 100% rename from conn/message/fixtures/test_must_gzip.golden rename to pkg/conn/message/fixtures/test_must_gzip.golden diff --git a/conn/message/fixtures/test_notify_type.golden b/pkg/conn/message/fixtures/test_notify_type.golden similarity index 100% rename from conn/message/fixtures/test_notify_type.golden rename to pkg/conn/message/fixtures/test_notify_type.golden diff --git a/conn/message/fixtures/test_notify_type_compressed.golden b/pkg/conn/message/fixtures/test_notify_type_compressed.golden similarity index 100% rename from conn/message/fixtures/test_notify_type_compressed.golden rename to pkg/conn/message/fixtures/test_notify_type_compressed.golden diff --git a/conn/message/fixtures/test_push_type.golden b/pkg/conn/message/fixtures/test_push_type.golden similarity index 100% rename from conn/message/fixtures/test_push_type.golden rename to pkg/conn/message/fixtures/test_push_type.golden diff --git a/conn/message/fixtures/test_push_type_compressed.golden b/pkg/conn/message/fixtures/test_push_type_compressed.golden similarity index 100% rename from conn/message/fixtures/test_push_type_compressed.golden rename to pkg/conn/message/fixtures/test_push_type_compressed.golden diff --git a/conn/message/fixtures/test_reponse_type.golden b/pkg/conn/message/fixtures/test_reponse_type.golden similarity index 100% rename from conn/message/fixtures/test_reponse_type.golden rename to pkg/conn/message/fixtures/test_reponse_type.golden diff --git a/conn/message/fixtures/test_reponse_type_with_data.golden b/pkg/conn/message/fixtures/test_reponse_type_with_data.golden similarity index 100% rename from conn/message/fixtures/test_reponse_type_with_data.golden rename to pkg/conn/message/fixtures/test_reponse_type_with_data.golden diff --git a/conn/message/fixtures/test_reponse_type_with_error.golden b/pkg/conn/message/fixtures/test_reponse_type_with_error.golden similarity index 100% rename from conn/message/fixtures/test_reponse_type_with_error.golden rename to pkg/conn/message/fixtures/test_reponse_type_with_error.golden diff --git a/conn/message/fixtures/test_reponse_type_with_id.golden b/pkg/conn/message/fixtures/test_reponse_type_with_id.golden similarity index 100% rename from conn/message/fixtures/test_reponse_type_with_id.golden rename to pkg/conn/message/fixtures/test_reponse_type_with_id.golden diff --git a/conn/message/fixtures/test_request_type.golden b/pkg/conn/message/fixtures/test_request_type.golden similarity index 100% rename from conn/message/fixtures/test_request_type.golden rename to pkg/conn/message/fixtures/test_request_type.golden diff --git a/conn/message/fixtures/test_request_type_compressed.golden b/pkg/conn/message/fixtures/test_request_type_compressed.golden similarity index 100% rename from conn/message/fixtures/test_request_type_compressed.golden rename to pkg/conn/message/fixtures/test_request_type_compressed.golden diff --git a/conn/message/fixtures/test_wrong_type.golden b/pkg/conn/message/fixtures/test_wrong_type.golden similarity index 100% rename from conn/message/fixtures/test_wrong_type.golden rename to pkg/conn/message/fixtures/test_wrong_type.golden diff --git a/conn/message/message.go b/pkg/conn/message/message.go similarity index 100% rename from conn/message/message.go rename to pkg/conn/message/message.go diff --git a/conn/message/message_encoder.go b/pkg/conn/message/message_encoder.go similarity index 95% rename from conn/message/message_encoder.go rename to pkg/conn/message/message_encoder.go index 5577c080..7b667159 100644 --- a/conn/message/message_encoder.go +++ b/pkg/conn/message/message_encoder.go @@ -23,7 +23,7 @@ package message import ( "encoding/binary" - "github.com/topfreegames/pitaya/v2/util/compression" + "github.com/topfreegames/pitaya/v3/pkg/util/compression" ) // Encoder interface @@ -60,7 +60,7 @@ func (me *MessagesEncoder) IsCompressionEnabled() bool { // | push |----011-| | // ------------------------------------------ // The figure above indicates that the bit does not affect the type of message. -// See ref: https://github.com/topfreegames/pitaya/v2/blob/master/docs/communication_protocol.md +// See ref: https://github.com/topfreegames/pitaya/v3/pkg/blob/master/docs/communication_protocol.md func (me *MessagesEncoder) Encode(message *Message) ([]byte, error) { if invalidType(message.Type) { return nil, ErrWrongMessageType @@ -129,7 +129,7 @@ func (me *MessagesEncoder) Decode(data []byte) (*Message, error) { } // Decode unmarshal the bytes slice to a message -// See ref: https://github.com/topfreegames/pitaya/v2/blob/master/docs/communication_protocol.md +// See ref: https://github.com/topfreegames/pitaya/v3/pkg/blob/master/docs/communication_protocol.md func Decode(data []byte) (*Message, error) { if len(data) < msgHeadLength { return nil, ErrInvalidMessage diff --git a/conn/message/message_test.go b/pkg/conn/message/message_test.go similarity index 99% rename from conn/message/message_test.go rename to pkg/conn/message/message_test.go index 7528870e..f29cd358 100644 --- a/conn/message/message_test.go +++ b/pkg/conn/message/message_test.go @@ -8,7 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/helpers" + "github.com/topfreegames/pitaya/v3/pkg/helpers" ) var update = flag.Bool("update", false, "update .golden files") diff --git a/conn/message/mocks/message_encoder.go b/pkg/conn/message/mocks/message_encoder.go similarity index 96% rename from conn/message/mocks/message_encoder.go rename to pkg/conn/message/mocks/message_encoder.go index 2c5ce885..b70a795d 100644 --- a/conn/message/mocks/message_encoder.go +++ b/pkg/conn/message/mocks/message_encoder.go @@ -6,7 +6,7 @@ package mocks import ( gomock "github.com/golang/mock/gomock" - message "github.com/topfreegames/pitaya/v2/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" reflect "reflect" ) diff --git a/conn/packet/constants.go b/pkg/conn/packet/constants.go similarity index 100% rename from conn/packet/constants.go rename to pkg/conn/packet/constants.go diff --git a/conn/packet/packet.go b/pkg/conn/packet/packet.go similarity index 100% rename from conn/packet/packet.go rename to pkg/conn/packet/packet.go diff --git a/conn/packet/packet_test.go b/pkg/conn/packet/packet_test.go similarity index 98% rename from conn/packet/packet_test.go rename to pkg/conn/packet/packet_test.go index 134a51b7..ff64f963 100644 --- a/conn/packet/packet_test.go +++ b/pkg/conn/packet/packet_test.go @@ -34,8 +34,8 @@ func TestNewPacket(t *testing.T) { func TestString(t *testing.T) { tables := []struct { - tp Type - data []byte + tp Type + data []byte strOut string }{ {Handshake, []byte{0x01}, fmt.Sprintf("Type: %d, Length: %d, Data: %s", Handshake, 1, string([]byte{0x01}))}, diff --git a/constants/const.go b/pkg/constants/const.go similarity index 100% rename from constants/const.go rename to pkg/constants/const.go diff --git a/constants/errors.go b/pkg/constants/errors.go similarity index 95% rename from constants/errors.go rename to pkg/constants/errors.go index b254cac0..81f52482 100644 --- a/constants/errors.go +++ b/pkg/constants/errors.go @@ -27,6 +27,7 @@ var ( ErrBindingNotFound = errors.New("binding for this user was not found in etcd") ErrBrokenPipe = errors.New("broken low-level pipe") ErrBufferExceed = errors.New("session send buffer exceed") + ErrCantSetNilData = errors.New("you can't set a nil data") ErrChangeDictionaryWhileRunning = errors.New("you shouldn't change the dictionary while the app is already running") ErrChangeRouteWhileRunning = errors.New("you shouldn't change routes while app is already running") ErrCloseClosedGroup = errors.New("close closed group") @@ -85,4 +86,6 @@ var ( ErrReceivedMsgSmallerThanExpected = errors.New("received less data than expected, EOF?") ErrReceivedMsgBiggerThanExpected = errors.New("received more data than expected") ErrConnectionClosed = errors.New("client connection closed") + ErrSidecarCallTimeout = errors.New("sidecar call to remote process timedout") + ErrSidecarNoCallbackInformation = errors.New("no callback information found for call, maybe it was cleaned by timeout") ) diff --git a/constants/version.go b/pkg/constants/version.go similarity index 100% rename from constants/version.go rename to pkg/constants/version.go diff --git a/context/context.go b/pkg/context/context.go similarity index 98% rename from context/context.go rename to pkg/context/context.go index eb4ad147..1551ddef 100644 --- a/context/context.go +++ b/pkg/context/context.go @@ -23,8 +23,7 @@ package context import ( "context" "encoding/json" - - "github.com/topfreegames/pitaya/v2/constants" + "github.com/topfreegames/pitaya/v3/pkg/constants" ) // AddToPropagateCtx adds a key and value that will be propagated through RPC calls diff --git a/context/context_test.go b/pkg/context/context_test.go similarity index 98% rename from context/context_test.go rename to pkg/context/context_test.go index 6adbd783..21d26e00 100644 --- a/context/context_test.go +++ b/pkg/context/context_test.go @@ -25,13 +25,13 @@ import ( "encoding/json" "errors" "flag" + "github.com/topfreegames/pitaya/v3/pkg/constants" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/helpers" + "github.com/topfreegames/pitaya/v3/pkg/helpers" ) var update = flag.Bool("update", false, "update .golden files") diff --git a/context/fixtures/one_element.golden b/pkg/context/fixtures/one_element.golden similarity index 100% rename from context/fixtures/one_element.golden rename to pkg/context/fixtures/one_element.golden diff --git a/context/fixtures/registered_struct.golden b/pkg/context/fixtures/registered_struct.golden similarity index 100% rename from context/fixtures/registered_struct.golden rename to pkg/context/fixtures/registered_struct.golden diff --git a/defaultpipelines/default_struct_validator.go b/pkg/defaultpipelines/default_struct_validator.go similarity index 100% rename from defaultpipelines/default_struct_validator.go rename to pkg/defaultpipelines/default_struct_validator.go diff --git a/defaultpipelines/default_struct_validator_test.go b/pkg/defaultpipelines/default_struct_validator_test.go similarity index 100% rename from defaultpipelines/default_struct_validator_test.go rename to pkg/defaultpipelines/default_struct_validator_test.go diff --git a/defaultpipelines/struct_validator.go b/pkg/defaultpipelines/struct_validator.go similarity index 100% rename from defaultpipelines/struct_validator.go rename to pkg/defaultpipelines/struct_validator.go diff --git a/deploy/kubernetes/example-backend.yaml b/pkg/deploy/kubernetes/example-backend.yaml similarity index 100% rename from deploy/kubernetes/example-backend.yaml rename to pkg/deploy/kubernetes/example-backend.yaml diff --git a/deploy/kubernetes/example-frontend.yaml b/pkg/deploy/kubernetes/example-frontend.yaml similarity index 100% rename from deploy/kubernetes/example-frontend.yaml rename to pkg/deploy/kubernetes/example-frontend.yaml diff --git a/docgenerator/descriptors.go b/pkg/docgenerator/descriptors.go similarity index 95% rename from docgenerator/descriptors.go rename to pkg/docgenerator/descriptors.go index 71ffed07..6849fc92 100644 --- a/docgenerator/descriptors.go +++ b/pkg/docgenerator/descriptors.go @@ -1,11 +1,11 @@ package docgenerator import ( + "github.com/topfreegames/pitaya/v3/pkg/constants" "reflect" "strings" "github.com/golang/protobuf/proto" - "github.com/topfreegames/pitaya/v2/constants" ) // ProtoDescriptors returns the descriptor for a given message name or .proto file diff --git a/docgenerator/descriptors_test.go b/pkg/docgenerator/descriptors_test.go similarity index 88% rename from docgenerator/descriptors_test.go rename to pkg/docgenerator/descriptors_test.go index 70177924..a42b0f85 100644 --- a/docgenerator/descriptors_test.go +++ b/pkg/docgenerator/descriptors_test.go @@ -1,11 +1,11 @@ package docgenerator import ( + "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/constants" - _ "github.com/topfreegames/pitaya/v2/protos" + _ "github.com/topfreegames/pitaya/v3/pkg/protos" ) func TestProtoDescriptors(t *testing.T) { diff --git a/docgenerator/generator.go b/pkg/docgenerator/generator.go similarity index 98% rename from docgenerator/generator.go rename to pkg/docgenerator/generator.go index 886121de..c153383f 100644 --- a/docgenerator/generator.go +++ b/pkg/docgenerator/generator.go @@ -22,12 +22,12 @@ package docgenerator import ( "encoding/json" + "github.com/topfreegames/pitaya/v3/pkg/component" "reflect" "strings" "unicode" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/route" + "github.com/topfreegames/pitaya/v3/pkg/route" ) type docs struct { diff --git a/docgenerator/generator_test.go b/pkg/docgenerator/generator_test.go similarity index 92% rename from docgenerator/generator_test.go rename to pkg/docgenerator/generator_test.go index d6fc7358..0ff16367 100644 --- a/docgenerator/generator_test.go +++ b/pkg/docgenerator/generator_test.go @@ -22,16 +22,16 @@ package docgenerator import ( "context" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" "testing" "time" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/protos/test" + "github.com/topfreegames/pitaya/v3/pkg/protos/test" ) type MyComp struct { - component.Base + component2.Base } type MyStruct struct { @@ -80,8 +80,8 @@ func (m *MyComp) RemoteStruct(ctx context.Context, ss *test.SomeStruct) (*test.S func TestHandlersDoc(t *testing.T) { t.Parallel() - handlerServices := map[string]*component.Service{} - s := component.NewService(&MyComp{}, []component.Option{}) + handlerServices := map[string]*component2.Service{} + s := component2.NewService(&MyComp{}, []component2.Option{}) err := s.ExtractHandler() assert.NoError(t, err) handlerServices[s.Name] = s @@ -167,8 +167,8 @@ func TestHandlersDoc(t *testing.T) { func TestHandlersDocTrue(t *testing.T) { t.Parallel() - handlerServices := map[string]*component.Service{} - s := component.NewService(&MyComp{}, []component.Option{}) + handlerServices := map[string]*component2.Service{} + s := component2.NewService(&MyComp{}, []component2.Option{}) err := s.ExtractHandler() assert.NoError(t, err) handlerServices[s.Name] = s @@ -253,8 +253,8 @@ func TestHandlersDocTrue(t *testing.T) { func TestRemotesDoc(t *testing.T) { t.Parallel() - remoteServices := map[string]*component.Service{} - s := component.NewService(&MyComp{}, []component.Option{}) + remoteServices := map[string]*component2.Service{} + s := component2.NewService(&MyComp{}, []component2.Option{}) err := s.ExtractRemote() assert.NoError(t, err) remoteServices[s.Name] = s @@ -280,8 +280,8 @@ func TestRemotesDoc(t *testing.T) { func TestRemotesDocTrue(t *testing.T) { t.Parallel() - remoteServices := map[string]*component.Service{} - s := component.NewService(&MyComp{}, []component.Option{}) + remoteServices := map[string]*component2.Service{} + s := component2.NewService(&MyComp{}, []component2.Option{}) err := s.ExtractRemote() assert.NoError(t, err) remoteServices[s.Name] = s diff --git a/pkg/docs.go b/pkg/docs.go new file mode 100644 index 00000000..3cb5d556 --- /dev/null +++ b/pkg/docs.go @@ -0,0 +1,55 @@ +package pkg + +import ( + "context" + "encoding/json" + "strings" + + "github.com/topfreegames/pitaya/v3/pkg/component" + pitayaprotos "github.com/topfreegames/pitaya/v3/pkg/protos" +) + +// Docs is the handler that will serve protos +type Docs struct { + component.Base +} + +// NewDocs creates a new docs handler +func NewDocs() *Docs { + return &Docs{} +} + +// Docs returns documentation +func (c *Docs) Docs(ctx context.Context) (*pitayaprotos.Doc, error) { + d, err := Documentation(true) + if err != nil { + return nil, err + } + doc, err := json.Marshal(d) + + if err != nil { + return nil, err + } + + return &pitayaprotos.Doc{Doc: string(doc)}, nil +} + +// Protos return protobuffers descriptors +func (c *Docs) Protos(ctx context.Context, message *pitayaprotos.ProtoNames) (*pitayaprotos.ProtoDescriptors, error) { + descriptors := make([][]byte, 0, len(message.GetName())) + + for _, name := range message.GetName() { + if !strings.HasPrefix(name, "protos.") { + name = strings.Replace(name, strings.SplitN(name, ".", 2)[0], "google.protobuf", 1) + } + protoDescriptor, err := Descriptor(name) + if err != nil { + return nil, err + } + descriptors = append(descriptors, protoDescriptor) + } + + return &pitayaprotos.ProtoDescriptors{ + Desc: descriptors, + }, nil +} diff --git a/errors/errors.go b/pkg/errors/errors.go similarity index 100% rename from errors/errors.go rename to pkg/errors/errors.go diff --git a/errors/errors_test.go b/pkg/errors/errors_test.go similarity index 100% rename from errors/errors_test.go rename to pkg/errors/errors_test.go diff --git a/group.go b/pkg/group.go similarity index 97% rename from group.go rename to pkg/group.go index 585fc971..82ce5903 100644 --- a/group.go +++ b/pkg/group.go @@ -18,14 +18,14 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/constants" "time" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) // Group represents an agglomeration of UIDs which is used to manage diff --git a/group_test.go b/pkg/group_test.go similarity index 98% rename from group_test.go rename to pkg/group_test.go index a0847318..045ca663 100644 --- a/group_test.go +++ b/pkg/group_test.go @@ -18,17 +18,17 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/session/mocks" ) func createGroupTestApp() Pitaya { diff --git a/groups/etcd_group_service.go b/pkg/groups/etcd_group_service.go similarity index 98% rename from groups/etcd_group_service.go rename to pkg/groups/etcd_group_service.go index 61c9436b..3b2892aa 100644 --- a/groups/etcd_group_service.go +++ b/pkg/groups/etcd_group_service.go @@ -3,15 +3,15 @@ package groups import ( "context" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" "sync" "time" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "go.etcd.io/etcd/api/v3/mvccpb" clientv3 "go.etcd.io/etcd/client/v3" "go.etcd.io/etcd/client/v3/namespace" - "go.etcd.io/etcd/api/v3/mvccpb" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" ) var ( diff --git a/groups/etcd_group_service_test.go b/pkg/groups/etcd_group_service_test.go similarity index 98% rename from groups/etcd_group_service_test.go rename to pkg/groups/etcd_group_service_test.go index 33b090be..8c58ea4e 100644 --- a/groups/etcd_group_service_test.go +++ b/pkg/groups/etcd_group_service_test.go @@ -21,9 +21,9 @@ package groups import ( + "github.com/topfreegames/pitaya/v3/pkg/config" "testing" - "github.com/topfreegames/pitaya/v2/config" "go.etcd.io/etcd/tests/v3/framework/integration" ) diff --git a/groups/group_service.go b/pkg/groups/group_service.go similarity index 100% rename from groups/group_service.go rename to pkg/groups/group_service.go diff --git a/groups/group_service_test.go b/pkg/groups/group_service_test.go similarity index 99% rename from groups/group_service_test.go rename to pkg/groups/group_service_test.go index 0e145f9b..3cbe2430 100644 --- a/groups/group_service_test.go +++ b/pkg/groups/group_service_test.go @@ -22,12 +22,11 @@ package groups import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" - - "github.com/topfreegames/pitaya/v2/constants" ) func testCreateDuplicatedGroup(gs GroupService, t *testing.T) { diff --git a/groups/memory_group_service.go b/pkg/groups/memory_group_service.go similarity index 98% rename from groups/memory_group_service.go rename to pkg/groups/memory_group_service.go index 6cde176b..44e2448b 100644 --- a/groups/memory_group_service.go +++ b/pkg/groups/memory_group_service.go @@ -2,11 +2,10 @@ package groups import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" "sync" "time" - - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" ) var ( diff --git a/groups/memory_group_service_test.go b/pkg/groups/memory_group_service_test.go similarity index 97% rename from groups/memory_group_service_test.go rename to pkg/groups/memory_group_service_test.go index 5075913b..7f7a3429 100644 --- a/groups/memory_group_service_test.go +++ b/pkg/groups/memory_group_service_test.go @@ -21,10 +21,9 @@ package groups import ( + "github.com/topfreegames/pitaya/v3/pkg/config" "os" "testing" - - "github.com/topfreegames/pitaya/v2/config" ) var memoryGroupService *MemoryGroupService diff --git a/helpers/helpers.go b/pkg/helpers/helpers.go similarity index 100% rename from helpers/helpers.go rename to pkg/helpers/helpers.go index 5b052475..c18808b3 100644 --- a/helpers/helpers.go +++ b/pkg/helpers/helpers.go @@ -14,10 +14,10 @@ import ( "testing" "time" - clientv3 "go.etcd.io/etcd/client/v3" - "go.etcd.io/etcd/tests/v3/framework/integration" "github.com/nats-io/nats-server/v2/server" gnatsd "github.com/nats-io/nats-server/v2/test" + clientv3 "go.etcd.io/etcd/client/v3" + "go.etcd.io/etcd/tests/v3/framework/integration" ) // GetFreePort returns a free port diff --git a/helpers/type_support.go b/pkg/helpers/type_support.go similarity index 100% rename from helpers/type_support.go rename to pkg/helpers/type_support.go diff --git a/interfaces/interfaces.go b/pkg/interfaces/interfaces.go similarity index 100% rename from interfaces/interfaces.go rename to pkg/interfaces/interfaces.go diff --git a/interfaces/mocks/interfaces.go b/pkg/interfaces/mocks/interfaces.go similarity index 100% rename from interfaces/mocks/interfaces.go rename to pkg/interfaces/mocks/interfaces.go diff --git a/kick.go b/pkg/kick.go similarity index 93% rename from kick.go rename to pkg/kick.go index b7cd66ba..91e1d134 100644 --- a/kick.go +++ b/pkg/kick.go @@ -18,14 +18,14 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/constants" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/protos" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/protos" ) // SendKickToUsers sends kick to an user array diff --git a/kick_test.go b/pkg/kick_test.go similarity index 94% rename from kick_test.go rename to pkg/kick_test.go index 895cdcf2..69e50fa3 100644 --- a/kick_test.go +++ b/pkg/kick_test.go @@ -18,20 +18,20 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "context" + clustermocks "github.com/topfreegames/pitaya/v3/pkg/cluster/mocks" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/stretchr/testify/assert" - clustermocks "github.com/topfreegames/pitaya/v2/cluster/mocks" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/protos" - sessionmocks "github.com/topfreegames/pitaya/v2/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/protos" + sessionmocks "github.com/topfreegames/pitaya/v3/pkg/session/mocks" ) func TestSendKickToUsersLocalSession(t *testing.T) { diff --git a/pkg/logger/interfaces/interfaces.go b/pkg/logger/interfaces/interfaces.go new file mode 100644 index 00000000..8daf1d64 --- /dev/null +++ b/pkg/logger/interfaces/interfaces.go @@ -0,0 +1,32 @@ +package interfaces + +// Logger interface for pitaya loggers +type Logger interface { + Fatal(format ...interface{}) + Fatalf(format string, args ...interface{}) + Fatalln(args ...interface{}) + + Debug(args ...interface{}) + Debugf(format string, args ...interface{}) + Debugln(args ...interface{}) + + Error(args ...interface{}) + Errorf(format string, args ...interface{}) + Errorln(args ...interface{}) + + Info(args ...interface{}) + Infof(format string, args ...interface{}) + Infoln(args ...interface{}) + + Warn(args ...interface{}) + Warnf(format string, args ...interface{}) + Warnln(args ...interface{}) + + Panic(args ...interface{}) + Panicf(format string, args ...interface{}) + Panicln(args ...interface{}) + + WithFields(fields map[string]interface{}) Logger + WithField(key string, value interface{}) Logger + WithError(err error) Logger +} diff --git a/logger/logger.go b/pkg/logger/logger.go similarity index 92% rename from logger/logger.go rename to pkg/logger/logger.go index 3732df82..b30a4d27 100644 --- a/logger/logger.go +++ b/pkg/logger/logger.go @@ -22,8 +22,8 @@ package logger import ( "github.com/sirupsen/logrus" - "github.com/topfreegames/pitaya/v2/logger/interfaces" - logruswrapper "github.com/topfreegames/pitaya/v2/logger/logrus" + "github.com/topfreegames/pitaya/v3/pkg/logger/interfaces" + logruswrapper "github.com/topfreegames/pitaya/v3/pkg/logger/logrus" ) // Log is the default logger diff --git a/logger/logger_test.go b/pkg/logger/logger_test.go similarity index 95% rename from logger/logger_test.go rename to pkg/logger/logger_test.go index 28d35774..69b0a898 100644 --- a/logger/logger_test.go +++ b/pkg/logger/logger_test.go @@ -24,7 +24,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - logruswrapper "github.com/topfreegames/pitaya/v2/logger/logrus" + logruswrapper "github.com/topfreegames/pitaya/v3/pkg/logger/logrus" ) func TestInitLogger(t *testing.T) { diff --git a/pkg/logger/logrus/logrus.go b/pkg/logger/logrus/logrus.go new file mode 100644 index 00000000..3a929ca2 --- /dev/null +++ b/pkg/logger/logrus/logrus.go @@ -0,0 +1,117 @@ +package logrus + +import ( + "github.com/sirupsen/logrus" + "github.com/topfreegames/pitaya/v3/pkg/logger/interfaces" +) + +type logrusImpl struct { + impl logrus.FieldLogger +} + +// New returns a new interfaces.Logger implementation based on logrus +func New() interfaces.Logger { + log := logrus.New() + return NewWithLogger(log) +} + +// NewWithEntry returns a new interfaces.Logger implementation based on a provided logrus entry instance +// Deprecated: NewWithEntry is deprecated. +func NewWithEntry(logger *logrus.Entry) interfaces.Logger { + return &logrusImpl{impl: logger} +} + +// NewWithLogger returns a new interfaces.Logger implementation based on a provided logrus instance +// Deprecated: NewWithLogger is deprecated. +func NewWithLogger(logger *logrus.Logger) interfaces.Logger { + return &logrusImpl{impl: logrus.NewEntry(logger)} +} + +// NewWithFieldLogger returns a new interfaces.Logger implementation based on a provided logrus instance +func NewWithFieldLogger(logger logrus.FieldLogger) interfaces.Logger { + return &logrusImpl{impl: logger} +} + +func (l *logrusImpl) Fatal(format ...interface{}) { + l.impl.Fatal(format...) +} + +func (l *logrusImpl) Fatalf(format string, args ...interface{}) { + l.impl.Fatalf(format, args...) +} + +func (l *logrusImpl) Fatalln(args ...interface{}) { + l.impl.Fatalln(args...) +} + +func (l *logrusImpl) Debug(args ...interface{}) { + l.impl.Debug(args...) +} + +func (l *logrusImpl) Debugf(format string, args ...interface{}) { + l.impl.Debugf(format, args...) +} + +func (l *logrusImpl) Debugln(args ...interface{}) { + l.impl.Debugln(args...) +} + +func (l *logrusImpl) Error(args ...interface{}) { + l.impl.Error(args...) +} + +func (l *logrusImpl) Errorf(format string, args ...interface{}) { + l.impl.Errorf(format, args...) +} + +func (l *logrusImpl) Errorln(args ...interface{}) { + l.impl.Errorln(args...) +} + +func (l *logrusImpl) Info(args ...interface{}) { + l.impl.Info(args...) +} + +func (l *logrusImpl) Infof(format string, args ...interface{}) { + l.impl.Infof(format, args...) +} + +func (l *logrusImpl) Infoln(args ...interface{}) { + l.impl.Infoln(args...) +} + +func (l *logrusImpl) Warn(args ...interface{}) { + l.impl.Warn(args...) +} + +func (l *logrusImpl) Warnf(format string, args ...interface{}) { + l.impl.Warnf(format, args...) +} + +func (l *logrusImpl) Warnln(args ...interface{}) { + l.impl.Warnln(args...) +} + +func (l *logrusImpl) Panic(args ...interface{}) { + l.impl.Panic(args...) +} + +func (l *logrusImpl) Panicf(format string, args ...interface{}) { + l.impl.Panicf(format, args...) +} + +func (l *logrusImpl) Panicln(args ...interface{}) { + l.impl.Panicln(args...) +} + +func (l *logrusImpl) WithFields(fields map[string]interface{}) interfaces.Logger { + return &logrusImpl{impl: l.impl.WithFields(fields)} +} + +func (l *logrusImpl) WithField(key string, value interface{}) interfaces.Logger { + return &logrusImpl{impl: l.impl.WithField(key, value)} +} + +func (l *logrusImpl) WithError(err error) interfaces.Logger { + return &logrusImpl{impl: l.impl.WithError(err)} +} diff --git a/metrics/constants.go b/pkg/metrics/constants.go similarity index 100% rename from metrics/constants.go rename to pkg/metrics/constants.go diff --git a/metrics/mocks/reporter.go b/pkg/metrics/mocks/reporter.go similarity index 83% rename from metrics/mocks/reporter.go rename to pkg/metrics/mocks/reporter.go index 81e186ac..428a93dc 100644 --- a/metrics/mocks/reporter.go +++ b/pkg/metrics/mocks/reporter.go @@ -1,38 +1,39 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/topfreegames/pitaya/v2/metrics (interfaces: Reporter) +// Source: github.com/topfreegames/pitaya/v3/pkg/metrics (interfaces: Reporter) // Package mocks is a generated GoMock package. package mocks import ( - gomock "github.com/golang/mock/gomock" reflect "reflect" + + gomock "github.com/golang/mock/gomock" ) -// MockReporter is a mock of Reporter interface +// MockReporter is a mock of Reporter interface. type MockReporter struct { ctrl *gomock.Controller recorder *MockReporterMockRecorder } -// MockReporterMockRecorder is the mock recorder for MockReporter +// MockReporterMockRecorder is the mock recorder for MockReporter. type MockReporterMockRecorder struct { mock *MockReporter } -// NewMockReporter creates a new mock instance +// NewMockReporter creates a new mock instance. func NewMockReporter(ctrl *gomock.Controller) *MockReporter { mock := &MockReporter{ctrl: ctrl} mock.recorder = &MockReporterMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use +// EXPECT returns an object that allows the caller to indicate expected use. func (m *MockReporter) EXPECT() *MockReporterMockRecorder { return m.recorder } -// ReportCount mocks base method +// ReportCount mocks base method. func (m *MockReporter) ReportCount(arg0 string, arg1 map[string]string, arg2 float64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReportCount", arg0, arg1, arg2) @@ -40,13 +41,13 @@ func (m *MockReporter) ReportCount(arg0 string, arg1 map[string]string, arg2 flo return ret0 } -// ReportCount indicates an expected call of ReportCount +// ReportCount indicates an expected call of ReportCount. func (mr *MockReporterMockRecorder) ReportCount(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportCount", reflect.TypeOf((*MockReporter)(nil).ReportCount), arg0, arg1, arg2) } -// ReportGauge mocks base method +// ReportGauge mocks base method. func (m *MockReporter) ReportGauge(arg0 string, arg1 map[string]string, arg2 float64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReportGauge", arg0, arg1, arg2) @@ -54,13 +55,13 @@ func (m *MockReporter) ReportGauge(arg0 string, arg1 map[string]string, arg2 flo return ret0 } -// ReportGauge indicates an expected call of ReportGauge +// ReportGauge indicates an expected call of ReportGauge. func (mr *MockReporterMockRecorder) ReportGauge(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportGauge", reflect.TypeOf((*MockReporter)(nil).ReportGauge), arg0, arg1, arg2) } -// ReportHistogram mocks base method +// ReportHistogram mocks base method. func (m *MockReporter) ReportHistogram(arg0 string, arg1 map[string]string, arg2 float64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReportHistogram", arg0, arg1, arg2) @@ -68,13 +69,13 @@ func (m *MockReporter) ReportHistogram(arg0 string, arg1 map[string]string, arg2 return ret0 } -// ReportHistogram indicates an expected call of ReportHistogram +// ReportHistogram indicates an expected call of ReportHistogram. func (mr *MockReporterMockRecorder) ReportHistogram(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportHistogram", reflect.TypeOf((*MockReporter)(nil).ReportHistogram), arg0, arg1, arg2) } -// ReportSummary mocks base method +// ReportSummary mocks base method. func (m *MockReporter) ReportSummary(arg0 string, arg1 map[string]string, arg2 float64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReportSummary", arg0, arg1, arg2) @@ -82,7 +83,7 @@ func (m *MockReporter) ReportSummary(arg0 string, arg1 map[string]string, arg2 f return ret0 } -// ReportSummary indicates an expected call of ReportSummary +// ReportSummary indicates an expected call of ReportSummary. func (mr *MockReporterMockRecorder) ReportSummary(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReportSummary", reflect.TypeOf((*MockReporter)(nil).ReportSummary), arg0, arg1, arg2) diff --git a/metrics/mocks/statsd_reporter.go b/pkg/metrics/mocks/statsd_reporter.go similarity index 82% rename from metrics/mocks/statsd_reporter.go rename to pkg/metrics/mocks/statsd_reporter.go index 2303005f..cabe9048 100644 --- a/metrics/mocks/statsd_reporter.go +++ b/pkg/metrics/mocks/statsd_reporter.go @@ -1,38 +1,39 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/topfreegames/pitaya/v2/metrics (interfaces: Client) +// Source: github.com/topfreegames/pitaya/v3/pkg/metrics (interfaces: Client) // Package mocks is a generated GoMock package. package mocks import ( - gomock "github.com/golang/mock/gomock" reflect "reflect" + + gomock "github.com/golang/mock/gomock" ) -// MockClient is a mock of Client interface +// MockClient is a mock of Client interface. type MockClient struct { ctrl *gomock.Controller recorder *MockClientMockRecorder } -// MockClientMockRecorder is the mock recorder for MockClient +// MockClientMockRecorder is the mock recorder for MockClient. type MockClientMockRecorder struct { mock *MockClient } -// NewMockClient creates a new mock instance +// NewMockClient creates a new mock instance. func NewMockClient(ctrl *gomock.Controller) *MockClient { mock := &MockClient{ctrl: ctrl} mock.recorder = &MockClientMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use +// EXPECT returns an object that allows the caller to indicate expected use. func (m *MockClient) EXPECT() *MockClientMockRecorder { return m.recorder } -// Count mocks base method +// Count mocks base method. func (m *MockClient) Count(arg0 string, arg1 int64, arg2 []string, arg3 float64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Count", arg0, arg1, arg2, arg3) @@ -40,13 +41,13 @@ func (m *MockClient) Count(arg0 string, arg1 int64, arg2 []string, arg3 float64) return ret0 } -// Count indicates an expected call of Count +// Count indicates an expected call of Count. func (mr *MockClientMockRecorder) Count(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Count", reflect.TypeOf((*MockClient)(nil).Count), arg0, arg1, arg2, arg3) } -// Gauge mocks base method +// Gauge mocks base method. func (m *MockClient) Gauge(arg0 string, arg1 float64, arg2 []string, arg3 float64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Gauge", arg0, arg1, arg2, arg3) @@ -54,13 +55,13 @@ func (m *MockClient) Gauge(arg0 string, arg1 float64, arg2 []string, arg3 float6 return ret0 } -// Gauge indicates an expected call of Gauge +// Gauge indicates an expected call of Gauge. func (mr *MockClientMockRecorder) Gauge(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Gauge", reflect.TypeOf((*MockClient)(nil).Gauge), arg0, arg1, arg2, arg3) } -// TimeInMilliseconds mocks base method +// TimeInMilliseconds mocks base method. func (m *MockClient) TimeInMilliseconds(arg0 string, arg1 float64, arg2 []string, arg3 float64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TimeInMilliseconds", arg0, arg1, arg2, arg3) @@ -68,7 +69,7 @@ func (m *MockClient) TimeInMilliseconds(arg0 string, arg1 float64, arg2 []string return ret0 } -// TimeInMilliseconds indicates an expected call of TimeInMilliseconds +// TimeInMilliseconds indicates an expected call of TimeInMilliseconds. func (mr *MockClientMockRecorder) TimeInMilliseconds(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TimeInMilliseconds", reflect.TypeOf((*MockClient)(nil).TimeInMilliseconds), arg0, arg1, arg2, arg3) diff --git a/metrics/models/models.go b/pkg/metrics/models/models.go similarity index 100% rename from metrics/models/models.go rename to pkg/metrics/models/models.go diff --git a/metrics/prometheus_reporter.go b/pkg/metrics/prometheus_reporter.go similarity index 98% rename from metrics/prometheus_reporter.go rename to pkg/metrics/prometheus_reporter.go index 4b8c9d4a..cd26f58a 100644 --- a/metrics/prometheus_reporter.go +++ b/pkg/metrics/prometheus_reporter.go @@ -22,16 +22,16 @@ package metrics import ( "fmt" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" "net/http" "sync" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/metrics/models" + "github.com/topfreegames/pitaya/v3/pkg/metrics/models" ) var ( diff --git a/metrics/report.go b/pkg/metrics/report.go similarity index 96% rename from metrics/report.go rename to pkg/metrics/report.go index 4791851a..93815584 100644 --- a/metrics/report.go +++ b/pkg/metrics/report.go @@ -22,13 +22,11 @@ package metrics import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" + "github.com/topfreegames/pitaya/v3/pkg/errors" "runtime" "time" - - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/errors" - - pcontext "github.com/topfreegames/pitaya/v2/context" ) // ReportTimingFromCtx reports the latency from the context diff --git a/metrics/report_test.go b/pkg/metrics/report_test.go similarity index 96% rename from metrics/report_test.go rename to pkg/metrics/report_test.go index e71fa4bc..9a2303b8 100644 --- a/metrics/report_test.go +++ b/pkg/metrics/report_test.go @@ -23,16 +23,16 @@ package metrics import ( "context" "errors" + "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "testing" "time" "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/constants" - pcontext "github.com/topfreegames/pitaya/v2/context" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/metrics/mocks" + "github.com/topfreegames/pitaya/v3/pkg/metrics/mocks" ) func TestReportTimingFromCtx(t *testing.T) { diff --git a/metrics/reporter_interfaces.go b/pkg/metrics/reporter_interfaces.go similarity index 100% rename from metrics/reporter_interfaces.go rename to pkg/metrics/reporter_interfaces.go diff --git a/metrics/statsd_reporter.go b/pkg/metrics/statsd_reporter.go similarity index 96% rename from metrics/statsd_reporter.go rename to pkg/metrics/statsd_reporter.go index 136984ac..3add6401 100644 --- a/metrics/statsd_reporter.go +++ b/pkg/metrics/statsd_reporter.go @@ -22,11 +22,11 @@ package metrics import ( "fmt" - "github.com/topfreegames/pitaya/v2/constants" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" "github.com/DataDog/datadog-go/statsd" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) // Client is the interface to required dogstatsd functions diff --git a/metrics/statsd_reporter_test.go b/pkg/metrics/statsd_reporter_test.go similarity index 98% rename from metrics/statsd_reporter_test.go rename to pkg/metrics/statsd_reporter_test.go index 20545f2e..dc758185 100644 --- a/metrics/statsd_reporter_test.go +++ b/pkg/metrics/statsd_reporter_test.go @@ -23,14 +23,14 @@ package metrics import ( "errors" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/config" "testing" "time" "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/config" - metricsmocks "github.com/topfreegames/pitaya/v2/metrics/mocks" + metricsmocks "github.com/topfreegames/pitaya/v3/pkg/metrics/mocks" ) func TestNewStatsdReporter(t *testing.T) { diff --git a/mocks/acceptor.go b/pkg/mocks/acceptor.go similarity index 81% rename from mocks/acceptor.go rename to pkg/mocks/acceptor.go index 516d0e89..1cd6558c 100644 --- a/mocks/acceptor.go +++ b/pkg/mocks/acceptor.go @@ -1,41 +1,42 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/topfreegames/pitaya/v2/acceptor (interfaces: PlayerConn,Acceptor) +// Source: github.com/topfreegames/pitaya/v3/pkg/acceptor (interfaces: PlayerConn,Acceptor) // Package mocks is a generated GoMock package. package mocks import ( - gomock "github.com/golang/mock/gomock" - acceptor "github.com/topfreegames/pitaya/v2/acceptor" net "net" reflect "reflect" time "time" + + gomock "github.com/golang/mock/gomock" + acceptor "github.com/topfreegames/pitaya/v3/pkg/acceptor" ) -// MockPlayerConn is a mock of PlayerConn interface +// MockPlayerConn is a mock of PlayerConn interface. type MockPlayerConn struct { ctrl *gomock.Controller recorder *MockPlayerConnMockRecorder } -// MockPlayerConnMockRecorder is the mock recorder for MockPlayerConn +// MockPlayerConnMockRecorder is the mock recorder for MockPlayerConn. type MockPlayerConnMockRecorder struct { mock *MockPlayerConn } -// NewMockPlayerConn creates a new mock instance +// NewMockPlayerConn creates a new mock instance. func NewMockPlayerConn(ctrl *gomock.Controller) *MockPlayerConn { mock := &MockPlayerConn{ctrl: ctrl} mock.recorder = &MockPlayerConnMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use +// EXPECT returns an object that allows the caller to indicate expected use. func (m *MockPlayerConn) EXPECT() *MockPlayerConnMockRecorder { return m.recorder } -// Close mocks base method +// Close mocks base method. func (m *MockPlayerConn) Close() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Close") @@ -43,13 +44,13 @@ func (m *MockPlayerConn) Close() error { return ret0 } -// Close indicates an expected call of Close +// Close indicates an expected call of Close. func (mr *MockPlayerConnMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockPlayerConn)(nil).Close)) } -// GetNextMessage mocks base method +// GetNextMessage mocks base method. func (m *MockPlayerConn) GetNextMessage() ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetNextMessage") @@ -58,13 +59,13 @@ func (m *MockPlayerConn) GetNextMessage() ([]byte, error) { return ret0, ret1 } -// GetNextMessage indicates an expected call of GetNextMessage +// GetNextMessage indicates an expected call of GetNextMessage. func (mr *MockPlayerConnMockRecorder) GetNextMessage() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNextMessage", reflect.TypeOf((*MockPlayerConn)(nil).GetNextMessage)) } -// LocalAddr mocks base method +// LocalAddr mocks base method. func (m *MockPlayerConn) LocalAddr() net.Addr { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LocalAddr") @@ -72,13 +73,13 @@ func (m *MockPlayerConn) LocalAddr() net.Addr { return ret0 } -// LocalAddr indicates an expected call of LocalAddr +// LocalAddr indicates an expected call of LocalAddr. func (mr *MockPlayerConnMockRecorder) LocalAddr() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LocalAddr", reflect.TypeOf((*MockPlayerConn)(nil).LocalAddr)) } -// Read mocks base method +// Read mocks base method. func (m *MockPlayerConn) Read(arg0 []byte) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Read", arg0) @@ -87,13 +88,13 @@ func (m *MockPlayerConn) Read(arg0 []byte) (int, error) { return ret0, ret1 } -// Read indicates an expected call of Read +// Read indicates an expected call of Read. func (mr *MockPlayerConnMockRecorder) Read(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockPlayerConn)(nil).Read), arg0) } -// RemoteAddr mocks base method +// RemoteAddr mocks base method. func (m *MockPlayerConn) RemoteAddr() net.Addr { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RemoteAddr") @@ -101,13 +102,13 @@ func (m *MockPlayerConn) RemoteAddr() net.Addr { return ret0 } -// RemoteAddr indicates an expected call of RemoteAddr +// RemoteAddr indicates an expected call of RemoteAddr. func (mr *MockPlayerConnMockRecorder) RemoteAddr() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoteAddr", reflect.TypeOf((*MockPlayerConn)(nil).RemoteAddr)) } -// SetDeadline mocks base method +// SetDeadline mocks base method. func (m *MockPlayerConn) SetDeadline(arg0 time.Time) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetDeadline", arg0) @@ -115,13 +116,13 @@ func (m *MockPlayerConn) SetDeadline(arg0 time.Time) error { return ret0 } -// SetDeadline indicates an expected call of SetDeadline +// SetDeadline indicates an expected call of SetDeadline. func (mr *MockPlayerConnMockRecorder) SetDeadline(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDeadline", reflect.TypeOf((*MockPlayerConn)(nil).SetDeadline), arg0) } -// SetReadDeadline mocks base method +// SetReadDeadline mocks base method. func (m *MockPlayerConn) SetReadDeadline(arg0 time.Time) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetReadDeadline", arg0) @@ -129,13 +130,13 @@ func (m *MockPlayerConn) SetReadDeadline(arg0 time.Time) error { return ret0 } -// SetReadDeadline indicates an expected call of SetReadDeadline +// SetReadDeadline indicates an expected call of SetReadDeadline. func (mr *MockPlayerConnMockRecorder) SetReadDeadline(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetReadDeadline", reflect.TypeOf((*MockPlayerConn)(nil).SetReadDeadline), arg0) } -// SetWriteDeadline mocks base method +// SetWriteDeadline mocks base method. func (m *MockPlayerConn) SetWriteDeadline(arg0 time.Time) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetWriteDeadline", arg0) @@ -143,13 +144,13 @@ func (m *MockPlayerConn) SetWriteDeadline(arg0 time.Time) error { return ret0 } -// SetWriteDeadline indicates an expected call of SetWriteDeadline +// SetWriteDeadline indicates an expected call of SetWriteDeadline. func (mr *MockPlayerConnMockRecorder) SetWriteDeadline(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetWriteDeadline", reflect.TypeOf((*MockPlayerConn)(nil).SetWriteDeadline), arg0) } -// Write mocks base method +// Write mocks base method. func (m *MockPlayerConn) Write(arg0 []byte) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Write", arg0) @@ -158,36 +159,36 @@ func (m *MockPlayerConn) Write(arg0 []byte) (int, error) { return ret0, ret1 } -// Write indicates an expected call of Write +// Write indicates an expected call of Write. func (mr *MockPlayerConnMockRecorder) Write(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockPlayerConn)(nil).Write), arg0) } -// MockAcceptor is a mock of Acceptor interface +// MockAcceptor is a mock of Acceptor interface. type MockAcceptor struct { ctrl *gomock.Controller recorder *MockAcceptorMockRecorder } -// MockAcceptorMockRecorder is the mock recorder for MockAcceptor +// MockAcceptorMockRecorder is the mock recorder for MockAcceptor. type MockAcceptorMockRecorder struct { mock *MockAcceptor } -// NewMockAcceptor creates a new mock instance +// NewMockAcceptor creates a new mock instance. func NewMockAcceptor(ctrl *gomock.Controller) *MockAcceptor { mock := &MockAcceptor{ctrl: ctrl} mock.recorder = &MockAcceptorMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use +// EXPECT returns an object that allows the caller to indicate expected use. func (m *MockAcceptor) EXPECT() *MockAcceptorMockRecorder { return m.recorder } -// GetAddr mocks base method +// GetAddr mocks base method. func (m *MockAcceptor) GetAddr() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAddr") @@ -195,13 +196,13 @@ func (m *MockAcceptor) GetAddr() string { return ret0 } -// GetAddr indicates an expected call of GetAddr +// GetAddr indicates an expected call of GetAddr. func (mr *MockAcceptorMockRecorder) GetAddr() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAddr", reflect.TypeOf((*MockAcceptor)(nil).GetAddr)) } -// GetConnChan mocks base method +// GetConnChan mocks base method. func (m *MockAcceptor) GetConnChan() chan acceptor.PlayerConn { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetConnChan") @@ -209,31 +210,31 @@ func (m *MockAcceptor) GetConnChan() chan acceptor.PlayerConn { return ret0 } -// GetConnChan indicates an expected call of GetConnChan +// GetConnChan indicates an expected call of GetConnChan. func (mr *MockAcceptorMockRecorder) GetConnChan() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConnChan", reflect.TypeOf((*MockAcceptor)(nil).GetConnChan)) } -// ListenAndServe mocks base method +// ListenAndServe mocks base method. func (m *MockAcceptor) ListenAndServe() { m.ctrl.T.Helper() m.ctrl.Call(m, "ListenAndServe") } -// ListenAndServe indicates an expected call of ListenAndServe +// ListenAndServe indicates an expected call of ListenAndServe. func (mr *MockAcceptorMockRecorder) ListenAndServe() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListenAndServe", reflect.TypeOf((*MockAcceptor)(nil).ListenAndServe)) } -// Stop mocks base method +// Stop mocks base method. func (m *MockAcceptor) Stop() { m.ctrl.T.Helper() m.ctrl.Call(m, "Stop") } -// Stop indicates an expected call of Stop +// Stop indicates an expected call of Stop. func (mr *MockAcceptorMockRecorder) Stop() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stop", reflect.TypeOf((*MockAcceptor)(nil).Stop)) diff --git a/mocks/app.go b/pkg/mocks/app.go similarity index 81% rename from mocks/app.go rename to pkg/mocks/app.go index b7fad59c..c65181d5 100644 --- a/mocks/app.go +++ b/pkg/mocks/app.go @@ -1,49 +1,52 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/topfreegames/pitaya/v2 (interfaces: Pitaya) +// Source: github.com/topfreegames/pitaya/v3/pkg (interfaces: Pitaya) // Package mocks is a generated GoMock package. package mocks import ( context "context" - gomock "github.com/golang/mock/gomock" - cluster "github.com/topfreegames/pitaya/v2/cluster" - component "github.com/topfreegames/pitaya/v2/component" - config "github.com/topfreegames/pitaya/v2/config" - interfaces "github.com/topfreegames/pitaya/v2/interfaces" - metrics "github.com/topfreegames/pitaya/v2/metrics" - router "github.com/topfreegames/pitaya/v2/router" - session "github.com/topfreegames/pitaya/v2/session" - worker "github.com/topfreegames/pitaya/v2/worker" - protoiface "google.golang.org/protobuf/runtime/protoiface" reflect "reflect" + sync "sync" time "time" + + gomock "github.com/golang/mock/gomock" + cluster "github.com/topfreegames/pitaya/v3/pkg/cluster" + component "github.com/topfreegames/pitaya/v3/pkg/component" + config "github.com/topfreegames/pitaya/v3/pkg/config" + interfaces "github.com/topfreegames/pitaya/v3/pkg/interfaces" + metrics "github.com/topfreegames/pitaya/v3/pkg/metrics" + protos "github.com/topfreegames/pitaya/v3/pkg/protos" + router "github.com/topfreegames/pitaya/v3/pkg/router" + session "github.com/topfreegames/pitaya/v3/pkg/session" + worker "github.com/topfreegames/pitaya/v3/pkg/worker" + protoiface "google.golang.org/protobuf/runtime/protoiface" ) -// MockPitaya is a mock of Pitaya interface +// MockPitaya is a mock of Pitaya interface. type MockPitaya struct { ctrl *gomock.Controller recorder *MockPitayaMockRecorder } -// MockPitayaMockRecorder is the mock recorder for MockPitaya +// MockPitayaMockRecorder is the mock recorder for MockPitaya. type MockPitayaMockRecorder struct { mock *MockPitaya } -// NewMockPitaya creates a new mock instance +// NewMockPitaya creates a new mock instance. func NewMockPitaya(ctrl *gomock.Controller) *MockPitaya { mock := &MockPitaya{ctrl: ctrl} mock.recorder = &MockPitayaMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use +// EXPECT returns an object that allows the caller to indicate expected use. func (m *MockPitaya) EXPECT() *MockPitayaMockRecorder { return m.recorder } -// AddRoute mocks base method +// AddRoute mocks base method. func (m *MockPitaya) AddRoute(arg0 string, arg1 router.RoutingFunc) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddRoute", arg0, arg1) @@ -51,13 +54,13 @@ func (m *MockPitaya) AddRoute(arg0 string, arg1 router.RoutingFunc) error { return ret0 } -// AddRoute indicates an expected call of AddRoute +// AddRoute indicates an expected call of AddRoute. func (mr *MockPitayaMockRecorder) AddRoute(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRoute", reflect.TypeOf((*MockPitaya)(nil).AddRoute), arg0, arg1) } -// Documentation mocks base method +// Documentation mocks base method. func (m *MockPitaya) Documentation(arg0 bool) (map[string]interface{}, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Documentation", arg0) @@ -66,13 +69,13 @@ func (m *MockPitaya) Documentation(arg0 bool) (map[string]interface{}, error) { return ret0, ret1 } -// Documentation indicates an expected call of Documentation +// Documentation indicates an expected call of Documentation. func (mr *MockPitayaMockRecorder) Documentation(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Documentation", reflect.TypeOf((*MockPitaya)(nil).Documentation), arg0) } -// GetDieChan mocks base method +// GetDieChan mocks base method. func (m *MockPitaya) GetDieChan() chan bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetDieChan") @@ -80,13 +83,13 @@ func (m *MockPitaya) GetDieChan() chan bool { return ret0 } -// GetDieChan indicates an expected call of GetDieChan +// GetDieChan indicates an expected call of GetDieChan. func (mr *MockPitayaMockRecorder) GetDieChan() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDieChan", reflect.TypeOf((*MockPitaya)(nil).GetDieChan)) } -// GetMetricsReporters mocks base method +// GetMetricsReporters mocks base method. func (m *MockPitaya) GetMetricsReporters() []metrics.Reporter { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetMetricsReporters") @@ -94,13 +97,13 @@ func (m *MockPitaya) GetMetricsReporters() []metrics.Reporter { return ret0 } -// GetMetricsReporters indicates an expected call of GetMetricsReporters +// GetMetricsReporters indicates an expected call of GetMetricsReporters. func (mr *MockPitayaMockRecorder) GetMetricsReporters() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMetricsReporters", reflect.TypeOf((*MockPitaya)(nil).GetMetricsReporters)) } -// GetModule mocks base method +// GetModule mocks base method. func (m *MockPitaya) GetModule(arg0 string) (interfaces.Module, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetModule", arg0) @@ -109,13 +112,13 @@ func (m *MockPitaya) GetModule(arg0 string) (interfaces.Module, error) { return ret0, ret1 } -// GetModule indicates an expected call of GetModule +// GetModule indicates an expected call of GetModule. func (mr *MockPitayaMockRecorder) GetModule(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetModule", reflect.TypeOf((*MockPitaya)(nil).GetModule), arg0) } -// GetServer mocks base method +// GetServer mocks base method. func (m *MockPitaya) GetServer() *cluster.Server { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetServer") @@ -123,13 +126,13 @@ func (m *MockPitaya) GetServer() *cluster.Server { return ret0 } -// GetServer indicates an expected call of GetServer +// GetServer indicates an expected call of GetServer. func (mr *MockPitayaMockRecorder) GetServer() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServer", reflect.TypeOf((*MockPitaya)(nil).GetServer)) } -// GetServerByID mocks base method +// GetServerByID mocks base method. func (m *MockPitaya) GetServerByID(arg0 string) (*cluster.Server, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetServerByID", arg0) @@ -138,13 +141,13 @@ func (m *MockPitaya) GetServerByID(arg0 string) (*cluster.Server, error) { return ret0, ret1 } -// GetServerByID indicates an expected call of GetServerByID +// GetServerByID indicates an expected call of GetServerByID. func (mr *MockPitayaMockRecorder) GetServerByID(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServerByID", reflect.TypeOf((*MockPitaya)(nil).GetServerByID), arg0) } -// GetServerID mocks base method +// GetServerID mocks base method. func (m *MockPitaya) GetServerID() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetServerID") @@ -152,13 +155,13 @@ func (m *MockPitaya) GetServerID() string { return ret0 } -// GetServerID indicates an expected call of GetServerID +// GetServerID indicates an expected call of GetServerID. func (mr *MockPitayaMockRecorder) GetServerID() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServerID", reflect.TypeOf((*MockPitaya)(nil).GetServerID)) } -// GetServers mocks base method +// GetServers mocks base method. func (m *MockPitaya) GetServers() []*cluster.Server { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetServers") @@ -166,13 +169,13 @@ func (m *MockPitaya) GetServers() []*cluster.Server { return ret0 } -// GetServers indicates an expected call of GetServers +// GetServers indicates an expected call of GetServers. func (mr *MockPitayaMockRecorder) GetServers() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServers", reflect.TypeOf((*MockPitaya)(nil).GetServers)) } -// GetServersByType mocks base method +// GetServersByType mocks base method. func (m *MockPitaya) GetServersByType(arg0 string) (map[string]*cluster.Server, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetServersByType", arg0) @@ -181,13 +184,13 @@ func (m *MockPitaya) GetServersByType(arg0 string) (map[string]*cluster.Server, return ret0, ret1 } -// GetServersByType indicates an expected call of GetServersByType +// GetServersByType indicates an expected call of GetServersByType. func (mr *MockPitayaMockRecorder) GetServersByType(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetServersByType", reflect.TypeOf((*MockPitaya)(nil).GetServersByType), arg0) } -// GetSessionFromCtx mocks base method +// GetSessionFromCtx mocks base method. func (m *MockPitaya) GetSessionFromCtx(arg0 context.Context) session.Session { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSessionFromCtx", arg0) @@ -195,13 +198,13 @@ func (m *MockPitaya) GetSessionFromCtx(arg0 context.Context) session.Session { return ret0 } -// GetSessionFromCtx indicates an expected call of GetSessionFromCtx +// GetSessionFromCtx indicates an expected call of GetSessionFromCtx. func (mr *MockPitayaMockRecorder) GetSessionFromCtx(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSessionFromCtx", reflect.TypeOf((*MockPitaya)(nil).GetSessionFromCtx), arg0) } -// GroupAddMember mocks base method +// GroupAddMember mocks base method. func (m *MockPitaya) GroupAddMember(arg0 context.Context, arg1, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GroupAddMember", arg0, arg1, arg2) @@ -209,13 +212,13 @@ func (m *MockPitaya) GroupAddMember(arg0 context.Context, arg1, arg2 string) err return ret0 } -// GroupAddMember indicates an expected call of GroupAddMember +// GroupAddMember indicates an expected call of GroupAddMember. func (mr *MockPitayaMockRecorder) GroupAddMember(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupAddMember", reflect.TypeOf((*MockPitaya)(nil).GroupAddMember), arg0, arg1, arg2) } -// GroupBroadcast mocks base method +// GroupBroadcast mocks base method. func (m *MockPitaya) GroupBroadcast(arg0 context.Context, arg1, arg2, arg3 string, arg4 interface{}) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GroupBroadcast", arg0, arg1, arg2, arg3, arg4) @@ -223,13 +226,13 @@ func (m *MockPitaya) GroupBroadcast(arg0 context.Context, arg1, arg2, arg3 strin return ret0 } -// GroupBroadcast indicates an expected call of GroupBroadcast +// GroupBroadcast indicates an expected call of GroupBroadcast. func (mr *MockPitayaMockRecorder) GroupBroadcast(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupBroadcast", reflect.TypeOf((*MockPitaya)(nil).GroupBroadcast), arg0, arg1, arg2, arg3, arg4) } -// GroupContainsMember mocks base method +// GroupContainsMember mocks base method. func (m *MockPitaya) GroupContainsMember(arg0 context.Context, arg1, arg2 string) (bool, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GroupContainsMember", arg0, arg1, arg2) @@ -238,13 +241,13 @@ func (m *MockPitaya) GroupContainsMember(arg0 context.Context, arg1, arg2 string return ret0, ret1 } -// GroupContainsMember indicates an expected call of GroupContainsMember +// GroupContainsMember indicates an expected call of GroupContainsMember. func (mr *MockPitayaMockRecorder) GroupContainsMember(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupContainsMember", reflect.TypeOf((*MockPitaya)(nil).GroupContainsMember), arg0, arg1, arg2) } -// GroupCountMembers mocks base method +// GroupCountMembers mocks base method. func (m *MockPitaya) GroupCountMembers(arg0 context.Context, arg1 string) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GroupCountMembers", arg0, arg1) @@ -253,13 +256,13 @@ func (m *MockPitaya) GroupCountMembers(arg0 context.Context, arg1 string) (int, return ret0, ret1 } -// GroupCountMembers indicates an expected call of GroupCountMembers +// GroupCountMembers indicates an expected call of GroupCountMembers. func (mr *MockPitayaMockRecorder) GroupCountMembers(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupCountMembers", reflect.TypeOf((*MockPitaya)(nil).GroupCountMembers), arg0, arg1) } -// GroupCreate mocks base method +// GroupCreate mocks base method. func (m *MockPitaya) GroupCreate(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GroupCreate", arg0, arg1) @@ -267,13 +270,13 @@ func (m *MockPitaya) GroupCreate(arg0 context.Context, arg1 string) error { return ret0 } -// GroupCreate indicates an expected call of GroupCreate +// GroupCreate indicates an expected call of GroupCreate. func (mr *MockPitayaMockRecorder) GroupCreate(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupCreate", reflect.TypeOf((*MockPitaya)(nil).GroupCreate), arg0, arg1) } -// GroupCreateWithTTL mocks base method +// GroupCreateWithTTL mocks base method. func (m *MockPitaya) GroupCreateWithTTL(arg0 context.Context, arg1 string, arg2 time.Duration) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GroupCreateWithTTL", arg0, arg1, arg2) @@ -281,13 +284,13 @@ func (m *MockPitaya) GroupCreateWithTTL(arg0 context.Context, arg1 string, arg2 return ret0 } -// GroupCreateWithTTL indicates an expected call of GroupCreateWithTTL +// GroupCreateWithTTL indicates an expected call of GroupCreateWithTTL. func (mr *MockPitayaMockRecorder) GroupCreateWithTTL(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupCreateWithTTL", reflect.TypeOf((*MockPitaya)(nil).GroupCreateWithTTL), arg0, arg1, arg2) } -// GroupDelete mocks base method +// GroupDelete mocks base method. func (m *MockPitaya) GroupDelete(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GroupDelete", arg0, arg1) @@ -295,13 +298,13 @@ func (m *MockPitaya) GroupDelete(arg0 context.Context, arg1 string) error { return ret0 } -// GroupDelete indicates an expected call of GroupDelete +// GroupDelete indicates an expected call of GroupDelete. func (mr *MockPitayaMockRecorder) GroupDelete(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupDelete", reflect.TypeOf((*MockPitaya)(nil).GroupDelete), arg0, arg1) } -// GroupMembers mocks base method +// GroupMembers mocks base method. func (m *MockPitaya) GroupMembers(arg0 context.Context, arg1 string) ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GroupMembers", arg0, arg1) @@ -310,13 +313,13 @@ func (m *MockPitaya) GroupMembers(arg0 context.Context, arg1 string) ([]string, return ret0, ret1 } -// GroupMembers indicates an expected call of GroupMembers +// GroupMembers indicates an expected call of GroupMembers. func (mr *MockPitayaMockRecorder) GroupMembers(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupMembers", reflect.TypeOf((*MockPitaya)(nil).GroupMembers), arg0, arg1) } -// GroupRemoveAll mocks base method +// GroupRemoveAll mocks base method. func (m *MockPitaya) GroupRemoveAll(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GroupRemoveAll", arg0, arg1) @@ -324,13 +327,13 @@ func (m *MockPitaya) GroupRemoveAll(arg0 context.Context, arg1 string) error { return ret0 } -// GroupRemoveAll indicates an expected call of GroupRemoveAll +// GroupRemoveAll indicates an expected call of GroupRemoveAll. func (mr *MockPitayaMockRecorder) GroupRemoveAll(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupRemoveAll", reflect.TypeOf((*MockPitaya)(nil).GroupRemoveAll), arg0, arg1) } -// GroupRemoveMember mocks base method +// GroupRemoveMember mocks base method. func (m *MockPitaya) GroupRemoveMember(arg0 context.Context, arg1, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GroupRemoveMember", arg0, arg1, arg2) @@ -338,13 +341,13 @@ func (m *MockPitaya) GroupRemoveMember(arg0 context.Context, arg1, arg2 string) return ret0 } -// GroupRemoveMember indicates an expected call of GroupRemoveMember +// GroupRemoveMember indicates an expected call of GroupRemoveMember. func (mr *MockPitayaMockRecorder) GroupRemoveMember(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupRemoveMember", reflect.TypeOf((*MockPitaya)(nil).GroupRemoveMember), arg0, arg1, arg2) } -// GroupRenewTTL mocks base method +// GroupRenewTTL mocks base method. func (m *MockPitaya) GroupRenewTTL(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GroupRenewTTL", arg0, arg1) @@ -352,13 +355,13 @@ func (m *MockPitaya) GroupRenewTTL(arg0 context.Context, arg1 string) error { return ret0 } -// GroupRenewTTL indicates an expected call of GroupRenewTTL +// GroupRenewTTL indicates an expected call of GroupRenewTTL. func (mr *MockPitayaMockRecorder) GroupRenewTTL(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupRenewTTL", reflect.TypeOf((*MockPitaya)(nil).GroupRenewTTL), arg0, arg1) } -// IsRunning mocks base method +// IsRunning mocks base method. func (m *MockPitaya) IsRunning() bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IsRunning") @@ -366,13 +369,13 @@ func (m *MockPitaya) IsRunning() bool { return ret0 } -// IsRunning indicates an expected call of IsRunning +// IsRunning indicates an expected call of IsRunning. func (mr *MockPitayaMockRecorder) IsRunning() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsRunning", reflect.TypeOf((*MockPitaya)(nil).IsRunning)) } -// RPC mocks base method +// RPC mocks base method. func (m *MockPitaya) RPC(arg0 context.Context, arg1 string, arg2, arg3 protoiface.MessageV1) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RPC", arg0, arg1, arg2, arg3) @@ -380,13 +383,13 @@ func (m *MockPitaya) RPC(arg0 context.Context, arg1 string, arg2, arg3 protoifac return ret0 } -// RPC indicates an expected call of RPC +// RPC indicates an expected call of RPC. func (mr *MockPitayaMockRecorder) RPC(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RPC", reflect.TypeOf((*MockPitaya)(nil).RPC), arg0, arg1, arg2, arg3) } -// RPCTo mocks base method +// RPCTo mocks base method. func (m *MockPitaya) RPCTo(arg0 context.Context, arg1, arg2 string, arg3, arg4 protoiface.MessageV1) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RPCTo", arg0, arg1, arg2, arg3, arg4) @@ -394,13 +397,28 @@ func (m *MockPitaya) RPCTo(arg0 context.Context, arg1, arg2 string, arg3, arg4 p return ret0 } -// RPCTo indicates an expected call of RPCTo +// RPCTo indicates an expected call of RPCTo. func (mr *MockPitayaMockRecorder) RPCTo(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RPCTo", reflect.TypeOf((*MockPitaya)(nil).RPCTo), arg0, arg1, arg2, arg3, arg4) } -// Register mocks base method +// RawRPC mocks base method. +func (m *MockPitaya) RawRPC(arg0 context.Context, arg1, arg2 string, arg3 []byte) (*protos.Response, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RawRPC", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(*protos.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// RawRPC indicates an expected call of RawRPC. +func (mr *MockPitayaMockRecorder) RawRPC(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RawRPC", reflect.TypeOf((*MockPitaya)(nil).RawRPC), arg0, arg1, arg2, arg3) +} + +// Register mocks base method. func (m *MockPitaya) Register(arg0 component.Component, arg1 ...component.Option) { m.ctrl.T.Helper() varargs := []interface{}{arg0} @@ -410,14 +428,14 @@ func (m *MockPitaya) Register(arg0 component.Component, arg1 ...component.Option m.ctrl.Call(m, "Register", varargs...) } -// Register indicates an expected call of Register +// Register indicates an expected call of Register. func (mr *MockPitayaMockRecorder) Register(arg0 interface{}, arg1 ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{arg0}, arg1...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Register", reflect.TypeOf((*MockPitaya)(nil).Register), varargs...) } -// RegisterModule mocks base method +// RegisterModule mocks base method. func (m *MockPitaya) RegisterModule(arg0 interfaces.Module, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RegisterModule", arg0, arg1) @@ -425,13 +443,13 @@ func (m *MockPitaya) RegisterModule(arg0 interfaces.Module, arg1 string) error { return ret0 } -// RegisterModule indicates an expected call of RegisterModule +// RegisterModule indicates an expected call of RegisterModule. func (mr *MockPitayaMockRecorder) RegisterModule(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterModule", reflect.TypeOf((*MockPitaya)(nil).RegisterModule), arg0, arg1) } -// RegisterModuleAfter mocks base method +// RegisterModuleAfter mocks base method. func (m *MockPitaya) RegisterModuleAfter(arg0 interfaces.Module, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RegisterModuleAfter", arg0, arg1) @@ -439,13 +457,13 @@ func (m *MockPitaya) RegisterModuleAfter(arg0 interfaces.Module, arg1 string) er return ret0 } -// RegisterModuleAfter indicates an expected call of RegisterModuleAfter +// RegisterModuleAfter indicates an expected call of RegisterModuleAfter. func (mr *MockPitayaMockRecorder) RegisterModuleAfter(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterModuleAfter", reflect.TypeOf((*MockPitaya)(nil).RegisterModuleAfter), arg0, arg1) } -// RegisterModuleBefore mocks base method +// RegisterModuleBefore mocks base method. func (m *MockPitaya) RegisterModuleBefore(arg0 interfaces.Module, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RegisterModuleBefore", arg0, arg1) @@ -453,13 +471,13 @@ func (m *MockPitaya) RegisterModuleBefore(arg0 interfaces.Module, arg1 string) e return ret0 } -// RegisterModuleBefore indicates an expected call of RegisterModuleBefore +// RegisterModuleBefore indicates an expected call of RegisterModuleBefore. func (mr *MockPitayaMockRecorder) RegisterModuleBefore(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterModuleBefore", reflect.TypeOf((*MockPitaya)(nil).RegisterModuleBefore), arg0, arg1) } -// RegisterRPCJob mocks base method +// RegisterRPCJob mocks base method. func (m *MockPitaya) RegisterRPCJob(arg0 worker.RPCJob) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RegisterRPCJob", arg0) @@ -467,13 +485,13 @@ func (m *MockPitaya) RegisterRPCJob(arg0 worker.RPCJob) error { return ret0 } -// RegisterRPCJob indicates an expected call of RegisterRPCJob +// RegisterRPCJob indicates an expected call of RegisterRPCJob. func (mr *MockPitayaMockRecorder) RegisterRPCJob(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterRPCJob", reflect.TypeOf((*MockPitaya)(nil).RegisterRPCJob), arg0) } -// RegisterRemote mocks base method +// RegisterRemote mocks base method. func (m *MockPitaya) RegisterRemote(arg0 component.Component, arg1 ...component.Option) { m.ctrl.T.Helper() varargs := []interface{}{arg0} @@ -483,14 +501,14 @@ func (m *MockPitaya) RegisterRemote(arg0 component.Component, arg1 ...component. m.ctrl.Call(m, "RegisterRemote", varargs...) } -// RegisterRemote indicates an expected call of RegisterRemote +// RegisterRemote indicates an expected call of RegisterRemote. func (mr *MockPitayaMockRecorder) RegisterRemote(arg0 interface{}, arg1 ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{arg0}, arg1...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterRemote", reflect.TypeOf((*MockPitaya)(nil).RegisterRemote), varargs...) } -// ReliableRPC mocks base method +// ReliableRPC mocks base method. func (m *MockPitaya) ReliableRPC(arg0 string, arg1 map[string]interface{}, arg2, arg3 protoiface.MessageV1) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReliableRPC", arg0, arg1, arg2, arg3) @@ -499,13 +517,13 @@ func (m *MockPitaya) ReliableRPC(arg0 string, arg1 map[string]interface{}, arg2, return ret0, ret1 } -// ReliableRPC indicates an expected call of ReliableRPC +// ReliableRPC indicates an expected call of ReliableRPC. func (mr *MockPitayaMockRecorder) ReliableRPC(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReliableRPC", reflect.TypeOf((*MockPitaya)(nil).ReliableRPC), arg0, arg1, arg2, arg3) } -// ReliableRPCWithOptions mocks base method +// ReliableRPCWithOptions mocks base method. func (m *MockPitaya) ReliableRPCWithOptions(arg0 string, arg1 map[string]interface{}, arg2, arg3 protoiface.MessageV1, arg4 *config.EnqueueOpts) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ReliableRPCWithOptions", arg0, arg1, arg2, arg3, arg4) @@ -514,13 +532,13 @@ func (m *MockPitaya) ReliableRPCWithOptions(arg0 string, arg1 map[string]interfa return ret0, ret1 } -// ReliableRPCWithOptions indicates an expected call of ReliableRPCWithOptions +// ReliableRPCWithOptions indicates an expected call of ReliableRPCWithOptions. func (mr *MockPitayaMockRecorder) ReliableRPCWithOptions(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReliableRPCWithOptions", reflect.TypeOf((*MockPitaya)(nil).ReliableRPCWithOptions), arg0, arg1, arg2, arg3, arg4) } -// SendKickToUsers mocks base method +// SendKickToUsers mocks base method. func (m *MockPitaya) SendKickToUsers(arg0 []string, arg1 string) ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendKickToUsers", arg0, arg1) @@ -529,13 +547,13 @@ func (m *MockPitaya) SendKickToUsers(arg0 []string, arg1 string) ([]string, erro return ret0, ret1 } -// SendKickToUsers indicates an expected call of SendKickToUsers +// SendKickToUsers indicates an expected call of SendKickToUsers. func (mr *MockPitayaMockRecorder) SendKickToUsers(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendKickToUsers", reflect.TypeOf((*MockPitaya)(nil).SendKickToUsers), arg0, arg1) } -// SendPushToUsers mocks base method +// SendPushToUsers mocks base method. func (m *MockPitaya) SendPushToUsers(arg0 string, arg1 interface{}, arg2 []string, arg3 string) ([]string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SendPushToUsers", arg0, arg1, arg2, arg3) @@ -544,25 +562,25 @@ func (m *MockPitaya) SendPushToUsers(arg0 string, arg1 interface{}, arg2 []strin return ret0, ret1 } -// SendPushToUsers indicates an expected call of SendPushToUsers +// SendPushToUsers indicates an expected call of SendPushToUsers. func (mr *MockPitayaMockRecorder) SendPushToUsers(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendPushToUsers", reflect.TypeOf((*MockPitaya)(nil).SendPushToUsers), arg0, arg1, arg2, arg3) } -// SetDebug mocks base method +// SetDebug mocks base method. func (m *MockPitaya) SetDebug(arg0 bool) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetDebug", arg0) } -// SetDebug indicates an expected call of SetDebug +// SetDebug indicates an expected call of SetDebug. func (mr *MockPitayaMockRecorder) SetDebug(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDebug", reflect.TypeOf((*MockPitaya)(nil).SetDebug), arg0) } -// SetDictionary mocks base method +// SetDictionary mocks base method. func (m *MockPitaya) SetDictionary(arg0 map[string]uint16) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetDictionary", arg0) @@ -570,55 +588,57 @@ func (m *MockPitaya) SetDictionary(arg0 map[string]uint16) error { return ret0 } -// SetDictionary indicates an expected call of SetDictionary +// SetDictionary indicates an expected call of SetDictionary. func (mr *MockPitayaMockRecorder) SetDictionary(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDictionary", reflect.TypeOf((*MockPitaya)(nil).SetDictionary), arg0) } -// SetHeartbeatTime mocks base method +// SetHeartbeatTime mocks base method. func (m *MockPitaya) SetHeartbeatTime(arg0 time.Duration) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetHeartbeatTime", arg0) } -// SetHeartbeatTime indicates an expected call of SetHeartbeatTime +// SetHeartbeatTime indicates an expected call of SetHeartbeatTime. func (mr *MockPitayaMockRecorder) SetHeartbeatTime(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetHeartbeatTime", reflect.TypeOf((*MockPitaya)(nil).SetHeartbeatTime), arg0) } -// Shutdown mocks base method -func (m *MockPitaya) Shutdown() { +// Shutdown mocks base method. +func (m *MockPitaya) Shutdown() *sync.WaitGroup { m.ctrl.T.Helper() - m.ctrl.Call(m, "Shutdown") + ret := m.ctrl.Call(m, "Shutdown") + ret0, _ := ret[0].(*sync.WaitGroup) + return ret0 } -// Shutdown indicates an expected call of Shutdown +// Shutdown indicates an expected call of Shutdown. func (mr *MockPitayaMockRecorder) Shutdown() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Shutdown", reflect.TypeOf((*MockPitaya)(nil).Shutdown)) } -// Start mocks base method +// Start mocks base method. func (m *MockPitaya) Start() { m.ctrl.T.Helper() m.ctrl.Call(m, "Start") } -// Start indicates an expected call of Start +// Start indicates an expected call of Start. func (mr *MockPitayaMockRecorder) Start() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockPitaya)(nil).Start)) } -// StartWorker mocks base method +// StartWorker mocks base method. func (m *MockPitaya) StartWorker() { m.ctrl.T.Helper() m.ctrl.Call(m, "StartWorker") } -// StartWorker indicates an expected call of StartWorker +// StartWorker indicates an expected call of StartWorker. func (mr *MockPitayaMockRecorder) StartWorker() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartWorker", reflect.TypeOf((*MockPitaya)(nil).StartWorker)) diff --git a/module.go b/pkg/module.go similarity index 97% rename from module.go rename to pkg/module.go index 52f4419f..71703e7d 100644 --- a/module.go +++ b/pkg/module.go @@ -18,13 +18,13 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "fmt" - "github.com/topfreegames/pitaya/v2/interfaces" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) type moduleWrapper struct { diff --git a/module_test.go b/pkg/module_test.go similarity index 97% rename from module_test.go rename to pkg/module_test.go index d51c38e0..8c5db82f 100644 --- a/module_test.go +++ b/pkg/module_test.go @@ -18,14 +18,14 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( + "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/config" "testing" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" ) type MyMod struct { diff --git a/modules/api_docs_gen.go b/pkg/modules/api_docs_gen.go similarity index 94% rename from modules/api_docs_gen.go rename to pkg/modules/api_docs_gen.go index 74e4e313..6da6289e 100644 --- a/modules/api_docs_gen.go +++ b/pkg/modules/api_docs_gen.go @@ -21,8 +21,8 @@ package modules import ( - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/component" ) // APIDocsGen is a pitaya module that generates api docs for pitaya servers diff --git a/modules/base.go b/pkg/modules/base.go similarity index 100% rename from modules/base.go rename to pkg/modules/base.go diff --git a/modules/binary.go b/pkg/modules/binary.go similarity index 96% rename from modules/binary.go rename to pkg/modules/binary.go index 18c6166a..de6f0bd0 100644 --- a/modules/binary.go +++ b/pkg/modules/binary.go @@ -22,12 +22,12 @@ package modules import ( "bufio" + "github.com/topfreegames/pitaya/v3/pkg/constants" "os/exec" "syscall" "time" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) // Binary is a pitaya module that starts a binary as a child process and diff --git a/modules/binary_test.go b/pkg/modules/binary_test.go similarity index 100% rename from modules/binary_test.go rename to pkg/modules/binary_test.go diff --git a/modules/binding_storage.go b/pkg/modules/binding_storage.go similarity index 95% rename from modules/binding_storage.go rename to pkg/modules/binding_storage.go index c68eb2cc..ea3503b2 100644 --- a/modules/binding_storage.go +++ b/pkg/modules/binding_storage.go @@ -23,15 +23,15 @@ package modules import ( "context" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" "time" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/session" clientv3 "go.etcd.io/etcd/client/v3" "go.etcd.io/etcd/client/v3/namespace" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/session" ) // ETCDBindingStorage module that uses etcd to keep in which frontend server each user is bound diff --git a/modules/unique_session.go b/pkg/modules/unique_session.go similarity index 86% rename from modules/unique_session.go rename to pkg/modules/unique_session.go index ad681e2a..5228c906 100644 --- a/modules/unique_session.go +++ b/pkg/modules/unique_session.go @@ -22,21 +22,21 @@ package modules import ( "context" + cluster2 "github.com/topfreegames/pitaya/v3/pkg/cluster" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/session" + "github.com/topfreegames/pitaya/v3/pkg/session" ) // UniqueSession module watches for sessions using the same UID and kicks them type UniqueSession struct { Base - server *cluster.Server - rpcClient cluster.RPCClient + server *cluster2.Server + rpcClient cluster2.RPCClient sessionPool session.SessionPool } // NewUniqueSession creates a new unique session module -func NewUniqueSession(server *cluster.Server, rpcServer cluster.RPCServer, rpcClient cluster.RPCClient, sessionPool session.SessionPool) *UniqueSession { +func NewUniqueSession(server *cluster2.Server, rpcServer cluster2.RPCServer, rpcClient cluster2.RPCClient, sessionPool session.SessionPool) *UniqueSession { return &UniqueSession{ server: server, rpcClient: rpcClient, diff --git a/pkg/networkentity/mocks/networkentity.go b/pkg/networkentity/mocks/networkentity.go new file mode 100644 index 00000000..2b0415ec --- /dev/null +++ b/pkg/networkentity/mocks/networkentity.go @@ -0,0 +1,127 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/topfreegames/pitaya/v3/pkg/networkentity (interfaces: NetworkEntity) + +// Package mocks is a generated GoMock package. +package mocks + +import ( + context "context" + net "net" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + protos "github.com/topfreegames/pitaya/v3/pkg/protos" +) + +// MockNetworkEntity is a mock of NetworkEntity interface. +type MockNetworkEntity struct { + ctrl *gomock.Controller + recorder *MockNetworkEntityMockRecorder +} + +// MockNetworkEntityMockRecorder is the mock recorder for MockNetworkEntity. +type MockNetworkEntityMockRecorder struct { + mock *MockNetworkEntity +} + +// NewMockNetworkEntity creates a new mock instance. +func NewMockNetworkEntity(ctrl *gomock.Controller) *MockNetworkEntity { + mock := &MockNetworkEntity{ctrl: ctrl} + mock.recorder = &MockNetworkEntityMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockNetworkEntity) EXPECT() *MockNetworkEntityMockRecorder { + return m.recorder +} + +// Close mocks base method. +func (m *MockNetworkEntity) Close() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Close") + ret0, _ := ret[0].(error) + return ret0 +} + +// Close indicates an expected call of Close. +func (mr *MockNetworkEntityMockRecorder) Close() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockNetworkEntity)(nil).Close)) +} + +// Kick mocks base method. +func (m *MockNetworkEntity) Kick(arg0 context.Context) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Kick", arg0) + ret0, _ := ret[0].(error) + return ret0 +} + +// Kick indicates an expected call of Kick. +func (mr *MockNetworkEntityMockRecorder) Kick(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Kick", reflect.TypeOf((*MockNetworkEntity)(nil).Kick), arg0) +} + +// Push mocks base method. +func (m *MockNetworkEntity) Push(arg0 string, arg1 interface{}) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Push", arg0, arg1) + ret0, _ := ret[0].(error) + return ret0 +} + +// Push indicates an expected call of Push. +func (mr *MockNetworkEntityMockRecorder) Push(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Push", reflect.TypeOf((*MockNetworkEntity)(nil).Push), arg0, arg1) +} + +// RemoteAddr mocks base method. +func (m *MockNetworkEntity) RemoteAddr() net.Addr { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RemoteAddr") + ret0, _ := ret[0].(net.Addr) + return ret0 +} + +// RemoteAddr indicates an expected call of RemoteAddr. +func (mr *MockNetworkEntityMockRecorder) RemoteAddr() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoteAddr", reflect.TypeOf((*MockNetworkEntity)(nil).RemoteAddr)) +} + +// ResponseMID mocks base method. +func (m *MockNetworkEntity) ResponseMID(arg0 context.Context, arg1 uint, arg2 interface{}, arg3 ...bool) error { + m.ctrl.T.Helper() + varargs := []interface{}{arg0, arg1, arg2} + for _, a := range arg3 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "ResponseMID", varargs...) + ret0, _ := ret[0].(error) + return ret0 +} + +// ResponseMID indicates an expected call of ResponseMID. +func (mr *MockNetworkEntityMockRecorder) ResponseMID(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{arg0, arg1, arg2}, arg3...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResponseMID", reflect.TypeOf((*MockNetworkEntity)(nil).ResponseMID), varargs...) +} + +// SendRequest mocks base method. +func (m *MockNetworkEntity) SendRequest(arg0 context.Context, arg1, arg2 string, arg3 interface{}) (*protos.Response, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendRequest", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(*protos.Response) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// SendRequest indicates an expected call of SendRequest. +func (mr *MockNetworkEntityMockRecorder) SendRequest(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendRequest", reflect.TypeOf((*MockNetworkEntity)(nil).SendRequest), arg0, arg1, arg2, arg3) +} diff --git a/pkg/networkentity/networkentity.go b/pkg/networkentity/networkentity.go new file mode 100644 index 00000000..84aced9c --- /dev/null +++ b/pkg/networkentity/networkentity.go @@ -0,0 +1,18 @@ +package networkentity + +import ( + "context" + "net" + + "github.com/topfreegames/pitaya/v3/pkg/protos" +) + +// NetworkEntity represent low-level network instance +type NetworkEntity interface { + Push(route string, v interface{}) error + ResponseMID(ctx context.Context, mid uint, v interface{}, isError ...bool) error + Close() error + Kick(ctx context.Context) error + RemoteAddr() net.Addr + SendRequest(ctx context.Context, serverID, route string, v interface{}) (*protos.Response, error) +} diff --git a/pipeline/pipeline.go b/pkg/pipeline/pipeline.go similarity index 98% rename from pipeline/pipeline.go rename to pkg/pipeline/pipeline.go index 73e57c2f..64d5f1c7 100644 --- a/pipeline/pipeline.go +++ b/pkg/pipeline/pipeline.go @@ -23,7 +23,7 @@ package pipeline import ( "context" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) type ( diff --git a/pipeline/pipeline_test.go b/pkg/pipeline/pipeline_test.go similarity index 100% rename from pipeline/pipeline_test.go rename to pkg/pipeline/pipeline_test.go diff --git a/pkg/protos/bind.pb.go b/pkg/protos/bind.pb.go new file mode 100644 index 00000000..bb0bf99a --- /dev/null +++ b/pkg/protos/bind.pb.go @@ -0,0 +1,153 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: bind.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type BindMsg struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Uid string `protobuf:"bytes,1,opt,name=uid,proto3" json:"uid,omitempty"` + Fid string `protobuf:"bytes,2,opt,name=fid,proto3" json:"fid,omitempty"` +} + +func (x *BindMsg) Reset() { + *x = BindMsg{} + if protoimpl.UnsafeEnabled { + mi := &file_bind_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *BindMsg) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BindMsg) ProtoMessage() {} + +func (x *BindMsg) ProtoReflect() protoreflect.Message { + mi := &file_bind_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use BindMsg.ProtoReflect.Descriptor instead. +func (*BindMsg) Descriptor() ([]byte, []int) { + return file_bind_proto_rawDescGZIP(), []int{0} +} + +func (x *BindMsg) GetUid() string { + if x != nil { + return x.Uid + } + return "" +} + +func (x *BindMsg) GetFid() string { + if x != nil { + return x.Fid + } + return "" +} + +var File_bind_proto protoreflect.FileDescriptor + +var file_bind_proto_rawDesc = []byte{ + 0x0a, 0x0a, 0x62, 0x69, 0x6e, 0x64, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x73, 0x22, 0x2d, 0x0a, 0x07, 0x42, 0x69, 0x6e, 0x64, 0x4d, 0x73, 0x67, 0x12, + 0x10, 0x0a, 0x03, 0x75, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x75, 0x69, + 0x64, 0x12, 0x10, 0x0a, 0x03, 0x66, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, + 0x66, 0x69, 0x64, 0x42, 0x3c, 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, + 0x6d, 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, + 0x69, 0x74, 0x61, 0x79, 0x61, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, + 0xaa, 0x02, 0x0e, 0x4e, 0x50, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, + 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_bind_proto_rawDescOnce sync.Once + file_bind_proto_rawDescData = file_bind_proto_rawDesc +) + +func file_bind_proto_rawDescGZIP() []byte { + file_bind_proto_rawDescOnce.Do(func() { + file_bind_proto_rawDescData = protoimpl.X.CompressGZIP(file_bind_proto_rawDescData) + }) + return file_bind_proto_rawDescData +} + +var file_bind_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_bind_proto_goTypes = []interface{}{ + (*BindMsg)(nil), // 0: protos.BindMsg +} +var file_bind_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_bind_proto_init() } +func file_bind_proto_init() { + if File_bind_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_bind_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*BindMsg); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_bind_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_bind_proto_goTypes, + DependencyIndexes: file_bind_proto_depIdxs, + MessageInfos: file_bind_proto_msgTypes, + }.Build() + File_bind_proto = out.File + file_bind_proto_rawDesc = nil + file_bind_proto_goTypes = nil + file_bind_proto_depIdxs = nil +} diff --git a/pkg/protos/doc.pb.go b/pkg/protos/doc.pb.go new file mode 100644 index 00000000..ff4893df --- /dev/null +++ b/pkg/protos/doc.pb.go @@ -0,0 +1,144 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: doc.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Doc struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Doc string `protobuf:"bytes,1,opt,name=doc,proto3" json:"doc,omitempty"` +} + +func (x *Doc) Reset() { + *x = Doc{} + if protoimpl.UnsafeEnabled { + mi := &file_doc_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Doc) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Doc) ProtoMessage() {} + +func (x *Doc) ProtoReflect() protoreflect.Message { + mi := &file_doc_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Doc.ProtoReflect.Descriptor instead. +func (*Doc) Descriptor() ([]byte, []int) { + return file_doc_proto_rawDescGZIP(), []int{0} +} + +func (x *Doc) GetDoc() string { + if x != nil { + return x.Doc + } + return "" +} + +var File_doc_proto protoreflect.FileDescriptor + +var file_doc_proto_rawDesc = []byte{ + 0x0a, 0x09, 0x64, 0x6f, 0x63, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x73, 0x22, 0x17, 0x0a, 0x03, 0x44, 0x6f, 0x63, 0x12, 0x10, 0x0a, 0x03, 0x64, 0x6f, + 0x63, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x64, 0x6f, 0x63, 0x42, 0x3c, 0x5a, 0x29, + 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, + 0x65, 0x65, 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2f, 0x70, + 0x6b, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0xaa, 0x02, 0x0e, 0x4e, 0x50, 0x69, 0x74, + 0x61, 0x79, 0x61, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x33, +} + +var ( + file_doc_proto_rawDescOnce sync.Once + file_doc_proto_rawDescData = file_doc_proto_rawDesc +) + +func file_doc_proto_rawDescGZIP() []byte { + file_doc_proto_rawDescOnce.Do(func() { + file_doc_proto_rawDescData = protoimpl.X.CompressGZIP(file_doc_proto_rawDescData) + }) + return file_doc_proto_rawDescData +} + +var file_doc_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_doc_proto_goTypes = []interface{}{ + (*Doc)(nil), // 0: protos.Doc +} +var file_doc_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_doc_proto_init() } +func file_doc_proto_init() { + if File_doc_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_doc_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Doc); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_doc_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_doc_proto_goTypes, + DependencyIndexes: file_doc_proto_depIdxs, + MessageInfos: file_doc_proto_msgTypes, + }.Build() + File_doc_proto = out.File + file_doc_proto_rawDesc = nil + file_doc_proto_goTypes = nil + file_doc_proto_depIdxs = nil +} diff --git a/pkg/protos/docmsg.pb.go b/pkg/protos/docmsg.pb.go new file mode 100644 index 00000000..5f65b610 --- /dev/null +++ b/pkg/protos/docmsg.pb.go @@ -0,0 +1,145 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: docmsg.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type DocMsg struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + GetProtos bool `protobuf:"varint,1,opt,name=getProtos,proto3" json:"getProtos,omitempty"` +} + +func (x *DocMsg) Reset() { + *x = DocMsg{} + if protoimpl.UnsafeEnabled { + mi := &file_docmsg_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DocMsg) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DocMsg) ProtoMessage() {} + +func (x *DocMsg) ProtoReflect() protoreflect.Message { + mi := &file_docmsg_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DocMsg.ProtoReflect.Descriptor instead. +func (*DocMsg) Descriptor() ([]byte, []int) { + return file_docmsg_proto_rawDescGZIP(), []int{0} +} + +func (x *DocMsg) GetGetProtos() bool { + if x != nil { + return x.GetProtos + } + return false +} + +var File_docmsg_proto protoreflect.FileDescriptor + +var file_docmsg_proto_rawDesc = []byte{ + 0x0a, 0x0c, 0x64, 0x6f, 0x63, 0x6d, 0x73, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x22, 0x26, 0x0a, 0x06, 0x44, 0x6f, 0x63, 0x4d, 0x73, 0x67, + 0x12, 0x1c, 0x0a, 0x09, 0x67, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x08, 0x52, 0x09, 0x67, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x42, 0x3c, + 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, + 0x66, 0x72, 0x65, 0x65, 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, + 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0xaa, 0x02, 0x0e, 0x4e, 0x50, + 0x69, 0x74, 0x61, 0x79, 0x61, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x62, 0x06, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_docmsg_proto_rawDescOnce sync.Once + file_docmsg_proto_rawDescData = file_docmsg_proto_rawDesc +) + +func file_docmsg_proto_rawDescGZIP() []byte { + file_docmsg_proto_rawDescOnce.Do(func() { + file_docmsg_proto_rawDescData = protoimpl.X.CompressGZIP(file_docmsg_proto_rawDescData) + }) + return file_docmsg_proto_rawDescData +} + +var file_docmsg_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_docmsg_proto_goTypes = []interface{}{ + (*DocMsg)(nil), // 0: protos.DocMsg +} +var file_docmsg_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_docmsg_proto_init() } +func file_docmsg_proto_init() { + if File_docmsg_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_docmsg_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DocMsg); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_docmsg_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_docmsg_proto_goTypes, + DependencyIndexes: file_docmsg_proto_depIdxs, + MessageInfos: file_docmsg_proto_msgTypes, + }.Build() + File_docmsg_proto = out.File + file_docmsg_proto_rawDesc = nil + file_docmsg_proto_goTypes = nil + file_docmsg_proto_depIdxs = nil +} diff --git a/pkg/protos/error.pb.go b/pkg/protos/error.pb.go new file mode 100644 index 00000000..ccd5f67c --- /dev/null +++ b/pkg/protos/error.pb.go @@ -0,0 +1,171 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: error.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Error struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` + Msg string `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg,omitempty"` + Metadata map[string]string `protobuf:"bytes,3,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` +} + +func (x *Error) Reset() { + *x = Error{} + if protoimpl.UnsafeEnabled { + mi := &file_error_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Error) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Error) ProtoMessage() {} + +func (x *Error) ProtoReflect() protoreflect.Message { + mi := &file_error_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Error.ProtoReflect.Descriptor instead. +func (*Error) Descriptor() ([]byte, []int) { + return file_error_proto_rawDescGZIP(), []int{0} +} + +func (x *Error) GetCode() string { + if x != nil { + return x.Code + } + return "" +} + +func (x *Error) GetMsg() string { + if x != nil { + return x.Msg + } + return "" +} + +func (x *Error) GetMetadata() map[string]string { + if x != nil { + return x.Metadata + } + return nil +} + +var File_error_proto protoreflect.FileDescriptor + +var file_error_proto_rawDesc = []byte{ + 0x0a, 0x0b, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x22, 0xa3, 0x01, 0x0a, 0x05, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, + 0x12, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x63, + 0x6f, 0x64, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6d, 0x73, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x03, 0x6d, 0x73, 0x67, 0x12, 0x37, 0x0a, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, + 0x61, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, + 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x2e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, + 0x6e, 0x74, 0x72, 0x79, 0x52, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x1a, 0x3b, + 0x0a, 0x0d, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, + 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, + 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x42, 0x3c, 0x5a, 0x29, 0x67, + 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, + 0x65, 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2f, 0x70, 0x6b, + 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0xaa, 0x02, 0x0e, 0x4e, 0x50, 0x69, 0x74, 0x61, + 0x79, 0x61, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x33, +} + +var ( + file_error_proto_rawDescOnce sync.Once + file_error_proto_rawDescData = file_error_proto_rawDesc +) + +func file_error_proto_rawDescGZIP() []byte { + file_error_proto_rawDescOnce.Do(func() { + file_error_proto_rawDescData = protoimpl.X.CompressGZIP(file_error_proto_rawDescData) + }) + return file_error_proto_rawDescData +} + +var file_error_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_error_proto_goTypes = []interface{}{ + (*Error)(nil), // 0: protos.Error + nil, // 1: protos.Error.MetadataEntry +} +var file_error_proto_depIdxs = []int32{ + 1, // 0: protos.Error.metadata:type_name -> protos.Error.MetadataEntry + 1, // [1:1] is the sub-list for method output_type + 1, // [1:1] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_error_proto_init() } +func file_error_proto_init() { + if File_error_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_error_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Error); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_error_proto_rawDesc, + NumEnums: 0, + NumMessages: 2, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_error_proto_goTypes, + DependencyIndexes: file_error_proto_depIdxs, + MessageInfos: file_error_proto_msgTypes, + }.Build() + File_error_proto = out.File + file_error_proto_rawDesc = nil + file_error_proto_goTypes = nil + file_error_proto_depIdxs = nil +} diff --git a/pkg/protos/kick.pb.go b/pkg/protos/kick.pb.go new file mode 100644 index 00000000..a38429c1 --- /dev/null +++ b/pkg/protos/kick.pb.go @@ -0,0 +1,207 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: kick.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type KickMsg struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + UserId string `protobuf:"bytes,1,opt,name=userId,proto3" json:"userId,omitempty"` +} + +func (x *KickMsg) Reset() { + *x = KickMsg{} + if protoimpl.UnsafeEnabled { + mi := &file_kick_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *KickMsg) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*KickMsg) ProtoMessage() {} + +func (x *KickMsg) ProtoReflect() protoreflect.Message { + mi := &file_kick_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use KickMsg.ProtoReflect.Descriptor instead. +func (*KickMsg) Descriptor() ([]byte, []int) { + return file_kick_proto_rawDescGZIP(), []int{0} +} + +func (x *KickMsg) GetUserId() string { + if x != nil { + return x.UserId + } + return "" +} + +type KickAnswer struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Kicked bool `protobuf:"varint,1,opt,name=kicked,proto3" json:"kicked,omitempty"` +} + +func (x *KickAnswer) Reset() { + *x = KickAnswer{} + if protoimpl.UnsafeEnabled { + mi := &file_kick_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *KickAnswer) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*KickAnswer) ProtoMessage() {} + +func (x *KickAnswer) ProtoReflect() protoreflect.Message { + mi := &file_kick_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use KickAnswer.ProtoReflect.Descriptor instead. +func (*KickAnswer) Descriptor() ([]byte, []int) { + return file_kick_proto_rawDescGZIP(), []int{1} +} + +func (x *KickAnswer) GetKicked() bool { + if x != nil { + return x.Kicked + } + return false +} + +var File_kick_proto protoreflect.FileDescriptor + +var file_kick_proto_rawDesc = []byte{ + 0x0a, 0x0a, 0x6b, 0x69, 0x63, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x73, 0x22, 0x21, 0x0a, 0x07, 0x4b, 0x69, 0x63, 0x6b, 0x4d, 0x73, 0x67, 0x12, + 0x16, 0x0a, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x22, 0x24, 0x0a, 0x0a, 0x4b, 0x69, 0x63, 0x6b, 0x41, + 0x6e, 0x73, 0x77, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x6b, 0x69, 0x63, 0x6b, 0x65, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x06, 0x6b, 0x69, 0x63, 0x6b, 0x65, 0x64, 0x42, 0x3c, 0x5a, + 0x29, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, 0x66, + 0x72, 0x65, 0x65, 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2f, + 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0xaa, 0x02, 0x0e, 0x4e, 0x50, 0x69, + 0x74, 0x61, 0x79, 0x61, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, +} + +var ( + file_kick_proto_rawDescOnce sync.Once + file_kick_proto_rawDescData = file_kick_proto_rawDesc +) + +func file_kick_proto_rawDescGZIP() []byte { + file_kick_proto_rawDescOnce.Do(func() { + file_kick_proto_rawDescData = protoimpl.X.CompressGZIP(file_kick_proto_rawDescData) + }) + return file_kick_proto_rawDescData +} + +var file_kick_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_kick_proto_goTypes = []interface{}{ + (*KickMsg)(nil), // 0: protos.KickMsg + (*KickAnswer)(nil), // 1: protos.KickAnswer +} +var file_kick_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_kick_proto_init() } +func file_kick_proto_init() { + if File_kick_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_kick_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*KickMsg); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kick_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*KickAnswer); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_kick_proto_rawDesc, + NumEnums: 0, + NumMessages: 2, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_kick_proto_goTypes, + DependencyIndexes: file_kick_proto_depIdxs, + MessageInfos: file_kick_proto_msgTypes, + }.Build() + File_kick_proto = out.File + file_kick_proto_rawDesc = nil + file_kick_proto_goTypes = nil + file_kick_proto_depIdxs = nil +} diff --git a/protos/mocks/pitaya.go b/pkg/protos/mocks/pitaya.go similarity index 99% rename from protos/mocks/pitaya.go rename to pkg/protos/mocks/pitaya.go index be86d376..052f963d 100644 --- a/protos/mocks/pitaya.go +++ b/pkg/protos/mocks/pitaya.go @@ -8,7 +8,7 @@ import ( reflect "reflect" gomock "github.com/golang/mock/gomock" - protos "github.com/topfreegames/pitaya/v2/protos" + protos "github.com/topfreegames/pitaya/v3/pkg/protos" context "golang.org/x/net/context" grpc "google.golang.org/grpc" ) diff --git a/pkg/protos/msg.pb.go b/pkg/protos/msg.pb.go new file mode 100644 index 00000000..df0c4af6 --- /dev/null +++ b/pkg/protos/msg.pb.go @@ -0,0 +1,242 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: msg.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type MsgType int32 + +const ( + MsgType_MsgRequest MsgType = 0 + MsgType_MsgNotify MsgType = 1 + MsgType_MsgResponse MsgType = 2 + MsgType_MsgPush MsgType = 3 +) + +// Enum value maps for MsgType. +var ( + MsgType_name = map[int32]string{ + 0: "MsgRequest", + 1: "MsgNotify", + 2: "MsgResponse", + 3: "MsgPush", + } + MsgType_value = map[string]int32{ + "MsgRequest": 0, + "MsgNotify": 1, + "MsgResponse": 2, + "MsgPush": 3, + } +) + +func (x MsgType) Enum() *MsgType { + p := new(MsgType) + *p = x + return p +} + +func (x MsgType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (MsgType) Descriptor() protoreflect.EnumDescriptor { + return file_msg_proto_enumTypes[0].Descriptor() +} + +func (MsgType) Type() protoreflect.EnumType { + return &file_msg_proto_enumTypes[0] +} + +func (x MsgType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use MsgType.Descriptor instead. +func (MsgType) EnumDescriptor() ([]byte, []int) { + return file_msg_proto_rawDescGZIP(), []int{0} +} + +type Msg struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Route string `protobuf:"bytes,2,opt,name=route,proto3" json:"route,omitempty"` + Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` + Reply string `protobuf:"bytes,4,opt,name=reply,proto3" json:"reply,omitempty"` + Type MsgType `protobuf:"varint,5,opt,name=type,proto3,enum=protos.MsgType" json:"type,omitempty"` +} + +func (x *Msg) Reset() { + *x = Msg{} + if protoimpl.UnsafeEnabled { + mi := &file_msg_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Msg) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Msg) ProtoMessage() {} + +func (x *Msg) ProtoReflect() protoreflect.Message { + mi := &file_msg_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Msg.ProtoReflect.Descriptor instead. +func (*Msg) Descriptor() ([]byte, []int) { + return file_msg_proto_rawDescGZIP(), []int{0} +} + +func (x *Msg) GetId() uint64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Msg) GetRoute() string { + if x != nil { + return x.Route + } + return "" +} + +func (x *Msg) GetData() []byte { + if x != nil { + return x.Data + } + return nil +} + +func (x *Msg) GetReply() string { + if x != nil { + return x.Reply + } + return "" +} + +func (x *Msg) GetType() MsgType { + if x != nil { + return x.Type + } + return MsgType_MsgRequest +} + +var File_msg_proto protoreflect.FileDescriptor + +var file_msg_proto_rawDesc = []byte{ + 0x0a, 0x09, 0x6d, 0x73, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x73, 0x22, 0x7a, 0x0a, 0x03, 0x4d, 0x73, 0x67, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x02, 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x72, 0x6f, + 0x75, 0x74, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x72, 0x6f, 0x75, 0x74, 0x65, + 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, + 0x64, 0x61, 0x74, 0x61, 0x12, 0x14, 0x0a, 0x05, 0x72, 0x65, 0x70, 0x6c, 0x79, 0x18, 0x04, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x05, 0x72, 0x65, 0x70, 0x6c, 0x79, 0x12, 0x23, 0x0a, 0x04, 0x74, 0x79, + 0x70, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x0f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x73, 0x2e, 0x4d, 0x73, 0x67, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x2a, + 0x46, 0x0a, 0x07, 0x4d, 0x73, 0x67, 0x54, 0x79, 0x70, 0x65, 0x12, 0x0e, 0x0a, 0x0a, 0x4d, 0x73, + 0x67, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x10, 0x00, 0x12, 0x0d, 0x0a, 0x09, 0x4d, 0x73, + 0x67, 0x4e, 0x6f, 0x74, 0x69, 0x66, 0x79, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x4d, 0x73, 0x67, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x10, 0x02, 0x12, 0x0b, 0x0a, 0x07, 0x4d, 0x73, + 0x67, 0x50, 0x75, 0x73, 0x68, 0x10, 0x03, 0x42, 0x3c, 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, 0x75, + 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, 0x67, 0x61, 0x6d, + 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x73, 0xaa, 0x02, 0x0e, 0x4e, 0x50, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2e, 0x50, + 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_msg_proto_rawDescOnce sync.Once + file_msg_proto_rawDescData = file_msg_proto_rawDesc +) + +func file_msg_proto_rawDescGZIP() []byte { + file_msg_proto_rawDescOnce.Do(func() { + file_msg_proto_rawDescData = protoimpl.X.CompressGZIP(file_msg_proto_rawDescData) + }) + return file_msg_proto_rawDescData +} + +var file_msg_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_msg_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_msg_proto_goTypes = []interface{}{ + (MsgType)(0), // 0: protos.MsgType + (*Msg)(nil), // 1: protos.Msg +} +var file_msg_proto_depIdxs = []int32{ + 0, // 0: protos.Msg.type:type_name -> protos.MsgType + 1, // [1:1] is the sub-list for method output_type + 1, // [1:1] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_msg_proto_init() } +func file_msg_proto_init() { + if File_msg_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_msg_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Msg); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_msg_proto_rawDesc, + NumEnums: 1, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_msg_proto_goTypes, + DependencyIndexes: file_msg_proto_depIdxs, + EnumInfos: file_msg_proto_enumTypes, + MessageInfos: file_msg_proto_msgTypes, + }.Build() + File_msg_proto = out.File + file_msg_proto_rawDesc = nil + file_msg_proto_goTypes = nil + file_msg_proto_depIdxs = nil +} diff --git a/pkg/protos/pitaya.pb.go b/pkg/protos/pitaya.pb.go new file mode 100644 index 00000000..475a7062 --- /dev/null +++ b/pkg/protos/pitaya.pb.go @@ -0,0 +1,102 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: pitaya.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +var File_pitaya_proto protoreflect.FileDescriptor + +var file_pitaya_proto_rawDesc = []byte{ + 0x0a, 0x0c, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x1a, 0x0d, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x0e, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x0a, 0x70, 0x75, 0x73, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x1a, 0x0a, 0x62, 0x69, 0x6e, 0x64, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x0a, 0x6b, + 0x69, 0x63, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x32, 0xd2, 0x01, 0x0a, 0x06, 0x50, 0x69, + 0x74, 0x61, 0x79, 0x61, 0x12, 0x2b, 0x0a, 0x04, 0x43, 0x61, 0x6c, 0x6c, 0x12, 0x0f, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x10, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, + 0x00, 0x12, 0x2e, 0x0a, 0x0a, 0x50, 0x75, 0x73, 0x68, 0x54, 0x6f, 0x55, 0x73, 0x65, 0x72, 0x12, + 0x0c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x50, 0x75, 0x73, 0x68, 0x1a, 0x10, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, + 0x00, 0x12, 0x38, 0x0a, 0x11, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x42, 0x69, 0x6e, 0x64, + 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x12, 0x0f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, + 0x42, 0x69, 0x6e, 0x64, 0x4d, 0x73, 0x67, 0x1a, 0x10, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, + 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x31, 0x0a, 0x08, 0x4b, + 0x69, 0x63, 0x6b, 0x55, 0x73, 0x65, 0x72, 0x12, 0x0f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, + 0x2e, 0x4b, 0x69, 0x63, 0x6b, 0x4d, 0x73, 0x67, 0x1a, 0x12, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x73, 0x2e, 0x4b, 0x69, 0x63, 0x6b, 0x41, 0x6e, 0x73, 0x77, 0x65, 0x72, 0x22, 0x00, 0x42, 0x3c, + 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, + 0x66, 0x72, 0x65, 0x65, 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, + 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0xaa, 0x02, 0x0e, 0x4e, 0x50, + 0x69, 0x74, 0x61, 0x79, 0x61, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x62, 0x06, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x33, +} + +var file_pitaya_proto_goTypes = []interface{}{ + (*Request)(nil), // 0: protos.Request + (*Push)(nil), // 1: protos.Push + (*BindMsg)(nil), // 2: protos.BindMsg + (*KickMsg)(nil), // 3: protos.KickMsg + (*Response)(nil), // 4: protos.Response + (*KickAnswer)(nil), // 5: protos.KickAnswer +} +var file_pitaya_proto_depIdxs = []int32{ + 0, // 0: protos.Pitaya.Call:input_type -> protos.Request + 1, // 1: protos.Pitaya.PushToUser:input_type -> protos.Push + 2, // 2: protos.Pitaya.SessionBindRemote:input_type -> protos.BindMsg + 3, // 3: protos.Pitaya.KickUser:input_type -> protos.KickMsg + 4, // 4: protos.Pitaya.Call:output_type -> protos.Response + 4, // 5: protos.Pitaya.PushToUser:output_type -> protos.Response + 4, // 6: protos.Pitaya.SessionBindRemote:output_type -> protos.Response + 5, // 7: protos.Pitaya.KickUser:output_type -> protos.KickAnswer + 4, // [4:8] is the sub-list for method output_type + 0, // [0:4] 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_pitaya_proto_init() } +func file_pitaya_proto_init() { + if File_pitaya_proto != nil { + return + } + file_request_proto_init() + file_response_proto_init() + file_push_proto_init() + file_bind_proto_init() + file_kick_proto_init() + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_pitaya_proto_rawDesc, + NumEnums: 0, + NumMessages: 0, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_pitaya_proto_goTypes, + DependencyIndexes: file_pitaya_proto_depIdxs, + }.Build() + File_pitaya_proto = out.File + file_pitaya_proto_rawDesc = nil + file_pitaya_proto_goTypes = nil + file_pitaya_proto_depIdxs = nil +} diff --git a/protos/pitaya.pb.go b/pkg/protos/pitaya_grpc.pb.go similarity index 66% rename from protos/pitaya.pb.go rename to pkg/protos/pitaya_grpc.pb.go index 4d3ad59e..b61019b2 100644 --- a/protos/pitaya.pb.go +++ b/pkg/protos/pitaya_grpc.pb.go @@ -1,39 +1,22 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: pitaya.proto +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. package protos -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - import ( - context "golang.org/x/net/context" + context "context" grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" ) -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 // PitayaClient is the client API for Pitaya service. // -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type PitayaClient interface { Call(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) PushToUser(ctx context.Context, in *Push, opts ...grpc.CallOption) (*Response, error) @@ -42,10 +25,10 @@ type PitayaClient interface { } type pitayaClient struct { - cc *grpc.ClientConn + cc grpc.ClientConnInterface } -func NewPitayaClient(cc *grpc.ClientConn) PitayaClient { +func NewPitayaClient(cc grpc.ClientConnInterface) PitayaClient { return &pitayaClient{cc} } @@ -86,6 +69,8 @@ func (c *pitayaClient) KickUser(ctx context.Context, in *KickMsg, opts ...grpc.C } // PitayaServer is the server API for Pitaya service. +// All implementations should embed UnimplementedPitayaServer +// for forward compatibility type PitayaServer interface { Call(context.Context, *Request) (*Response, error) PushToUser(context.Context, *Push) (*Response, error) @@ -93,8 +78,32 @@ type PitayaServer interface { KickUser(context.Context, *KickMsg) (*KickAnswer, error) } -func RegisterPitayaServer(s *grpc.Server, srv PitayaServer) { - s.RegisterService(&_Pitaya_serviceDesc, srv) +// UnimplementedPitayaServer should be embedded to have forward compatible implementations. +type UnimplementedPitayaServer struct { +} + +func (UnimplementedPitayaServer) Call(context.Context, *Request) (*Response, error) { + return nil, status.Errorf(codes.Unimplemented, "method Call not implemented") +} +func (UnimplementedPitayaServer) PushToUser(context.Context, *Push) (*Response, error) { + return nil, status.Errorf(codes.Unimplemented, "method PushToUser not implemented") +} +func (UnimplementedPitayaServer) SessionBindRemote(context.Context, *BindMsg) (*Response, error) { + return nil, status.Errorf(codes.Unimplemented, "method SessionBindRemote not implemented") +} +func (UnimplementedPitayaServer) KickUser(context.Context, *KickMsg) (*KickAnswer, error) { + return nil, status.Errorf(codes.Unimplemented, "method KickUser not implemented") +} + +// UnsafePitayaServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to PitayaServer will +// result in compilation errors. +type UnsafePitayaServer interface { + mustEmbedUnimplementedPitayaServer() +} + +func RegisterPitayaServer(s grpc.ServiceRegistrar, srv PitayaServer) { + s.RegisterService(&Pitaya_ServiceDesc, srv) } func _Pitaya_Call_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { @@ -169,7 +178,10 @@ func _Pitaya_KickUser_Handler(srv interface{}, ctx context.Context, dec func(int return interceptor(ctx, in, info, handler) } -var _Pitaya_serviceDesc = grpc.ServiceDesc{ +// Pitaya_ServiceDesc is the grpc.ServiceDesc for Pitaya service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Pitaya_ServiceDesc = grpc.ServiceDesc{ ServiceName: "protos.Pitaya", HandlerType: (*PitayaServer)(nil), Methods: []grpc.MethodDesc{ @@ -193,22 +205,3 @@ var _Pitaya_serviceDesc = grpc.ServiceDesc{ Streams: []grpc.StreamDesc{}, Metadata: "pitaya.proto", } - -func init() { proto.RegisterFile("pitaya.proto", fileDescriptor_pitaya_c66f1da1c2593b20) } - -var fileDescriptor_pitaya_c66f1da1c2593b20 = []byte{ - // 199 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x29, 0xc8, 0x2c, 0x49, - 0xac, 0x4c, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x53, 0xc5, 0x52, 0xbc, 0x45, - 0xa9, 0x85, 0xa5, 0xa9, 0xc5, 0x25, 0x10, 0x61, 0x29, 0xbe, 0xa2, 0xd4, 0xe2, 0x82, 0xfc, 0xbc, - 0xe2, 0x54, 0x28, 0x9f, 0xab, 0xa0, 0xb4, 0x38, 0x03, 0xc6, 0x4e, 0xca, 0xcc, 0x4b, 0x81, 0xb1, - 0xb3, 0x33, 0x93, 0xb3, 0x21, 0x6c, 0xa3, 0x4b, 0x8c, 0x5c, 0x6c, 0x01, 0x60, 0xb3, 0x85, 0xb4, - 0xb9, 0x58, 0x9c, 0x13, 0x73, 0x72, 0x84, 0xf8, 0x21, 0x52, 0xc5, 0x7a, 0x41, 0x10, 0xd3, 0xa5, - 0x04, 0x10, 0x02, 0x10, 0xf3, 0x95, 0x18, 0x84, 0xf4, 0xb8, 0xb8, 0x02, 0x4a, 0x8b, 0x33, 0x42, - 0xf2, 0x43, 0x8b, 0x53, 0x8b, 0x84, 0x78, 0x60, 0x2a, 0x40, 0x62, 0x58, 0xd5, 0x5b, 0x70, 0x09, - 0x06, 0xa7, 0x16, 0x17, 0x67, 0xe6, 0xe7, 0x39, 0x65, 0xe6, 0xa5, 0x04, 0xa5, 0xe6, 0xe6, 0x97, - 0xa4, 0x22, 0x6c, 0x02, 0x89, 0xf9, 0x16, 0xa7, 0x63, 0xd5, 0x69, 0xc8, 0xc5, 0xe1, 0x9d, 0x99, - 0x9c, 0x0d, 0xb6, 0x07, 0xae, 0x01, 0x24, 0x02, 0xd2, 0x20, 0x84, 0x2c, 0xe0, 0x98, 0x57, 0x5c, - 0x9e, 0x5a, 0xa4, 0xc4, 0x90, 0x04, 0x09, 0x1f, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x70, - 0x0c, 0x65, 0x3c, 0x36, 0x01, 0x00, 0x00, -} diff --git a/pkg/protos/protodescriptor.pb.go b/pkg/protos/protodescriptor.pb.go new file mode 100644 index 00000000..55e85809 --- /dev/null +++ b/pkg/protos/protodescriptor.pb.go @@ -0,0 +1,333 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: protodescriptor.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// Descriptor proto used to retrieve zipped proto descriptors remotely +type ProtoDescriptor struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Desc []byte `protobuf:"bytes,1,opt,name=desc,proto3" json:"desc,omitempty"` +} + +func (x *ProtoDescriptor) Reset() { + *x = ProtoDescriptor{} + if protoimpl.UnsafeEnabled { + mi := &file_protodescriptor_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ProtoDescriptor) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ProtoDescriptor) ProtoMessage() {} + +func (x *ProtoDescriptor) ProtoReflect() protoreflect.Message { + mi := &file_protodescriptor_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ProtoDescriptor.ProtoReflect.Descriptor instead. +func (*ProtoDescriptor) Descriptor() ([]byte, []int) { + return file_protodescriptor_proto_rawDescGZIP(), []int{0} +} + +func (x *ProtoDescriptor) GetDesc() []byte { + if x != nil { + return x.Desc + } + return nil +} + +type ProtoName struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` +} + +func (x *ProtoName) Reset() { + *x = ProtoName{} + if protoimpl.UnsafeEnabled { + mi := &file_protodescriptor_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ProtoName) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ProtoName) ProtoMessage() {} + +func (x *ProtoName) ProtoReflect() protoreflect.Message { + mi := &file_protodescriptor_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ProtoName.ProtoReflect.Descriptor instead. +func (*ProtoName) Descriptor() ([]byte, []int) { + return file_protodescriptor_proto_rawDescGZIP(), []int{1} +} + +func (x *ProtoName) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +type ProtoDescriptors struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Desc [][]byte `protobuf:"bytes,1,rep,name=desc,proto3" json:"desc,omitempty"` +} + +func (x *ProtoDescriptors) Reset() { + *x = ProtoDescriptors{} + if protoimpl.UnsafeEnabled { + mi := &file_protodescriptor_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ProtoDescriptors) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ProtoDescriptors) ProtoMessage() {} + +func (x *ProtoDescriptors) ProtoReflect() protoreflect.Message { + mi := &file_protodescriptor_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ProtoDescriptors.ProtoReflect.Descriptor instead. +func (*ProtoDescriptors) Descriptor() ([]byte, []int) { + return file_protodescriptor_proto_rawDescGZIP(), []int{2} +} + +func (x *ProtoDescriptors) GetDesc() [][]byte { + if x != nil { + return x.Desc + } + return nil +} + +type ProtoNames struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name []string `protobuf:"bytes,1,rep,name=name,proto3" json:"name,omitempty"` +} + +func (x *ProtoNames) Reset() { + *x = ProtoNames{} + if protoimpl.UnsafeEnabled { + mi := &file_protodescriptor_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ProtoNames) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ProtoNames) ProtoMessage() {} + +func (x *ProtoNames) ProtoReflect() protoreflect.Message { + mi := &file_protodescriptor_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ProtoNames.ProtoReflect.Descriptor instead. +func (*ProtoNames) Descriptor() ([]byte, []int) { + return file_protodescriptor_proto_rawDescGZIP(), []int{3} +} + +func (x *ProtoNames) GetName() []string { + if x != nil { + return x.Name + } + return nil +} + +var File_protodescriptor_proto protoreflect.FileDescriptor + +var file_protodescriptor_proto_rawDesc = []byte{ + 0x0a, 0x15, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, + 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x22, + 0x25, 0x0a, 0x0f, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, + 0x6f, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x65, 0x73, 0x63, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, + 0x52, 0x04, 0x64, 0x65, 0x73, 0x63, 0x22, 0x1f, 0x0a, 0x09, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x4e, + 0x61, 0x6d, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x26, 0x0a, 0x10, 0x50, 0x72, 0x6f, 0x74, 0x6f, + 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6f, 0x72, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x64, + 0x65, 0x73, 0x63, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x65, 0x73, 0x63, 0x22, + 0x20, 0x0a, 0x0a, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x12, 0x12, 0x0a, + 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, + 0x65, 0x42, 0x3c, 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, + 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, + 0x61, 0x79, 0x61, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0xaa, 0x02, + 0x0e, 0x4e, 0x50, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x62, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_protodescriptor_proto_rawDescOnce sync.Once + file_protodescriptor_proto_rawDescData = file_protodescriptor_proto_rawDesc +) + +func file_protodescriptor_proto_rawDescGZIP() []byte { + file_protodescriptor_proto_rawDescOnce.Do(func() { + file_protodescriptor_proto_rawDescData = protoimpl.X.CompressGZIP(file_protodescriptor_proto_rawDescData) + }) + return file_protodescriptor_proto_rawDescData +} + +var file_protodescriptor_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_protodescriptor_proto_goTypes = []interface{}{ + (*ProtoDescriptor)(nil), // 0: protos.ProtoDescriptor + (*ProtoName)(nil), // 1: protos.ProtoName + (*ProtoDescriptors)(nil), // 2: protos.ProtoDescriptors + (*ProtoNames)(nil), // 3: protos.ProtoNames +} +var file_protodescriptor_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_protodescriptor_proto_init() } +func file_protodescriptor_proto_init() { + if File_protodescriptor_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_protodescriptor_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ProtoDescriptor); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_protodescriptor_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ProtoName); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_protodescriptor_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ProtoDescriptors); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_protodescriptor_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ProtoNames); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_protodescriptor_proto_rawDesc, + NumEnums: 0, + NumMessages: 4, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_protodescriptor_proto_goTypes, + DependencyIndexes: file_protodescriptor_proto_depIdxs, + MessageInfos: file_protodescriptor_proto_msgTypes, + }.Build() + File_protodescriptor_proto = out.File + file_protodescriptor_proto_rawDesc = nil + file_protodescriptor_proto_goTypes = nil + file_protodescriptor_proto_depIdxs = nil +} diff --git a/pkg/protos/push.pb.go b/pkg/protos/push.pb.go new file mode 100644 index 00000000..c67c32ac --- /dev/null +++ b/pkg/protos/push.pb.go @@ -0,0 +1,162 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: push.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Push struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Route string `protobuf:"bytes,1,opt,name=route,proto3" json:"route,omitempty"` + Uid string `protobuf:"bytes,2,opt,name=uid,proto3" json:"uid,omitempty"` + Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` +} + +func (x *Push) Reset() { + *x = Push{} + if protoimpl.UnsafeEnabled { + mi := &file_push_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Push) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Push) ProtoMessage() {} + +func (x *Push) ProtoReflect() protoreflect.Message { + mi := &file_push_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Push.ProtoReflect.Descriptor instead. +func (*Push) Descriptor() ([]byte, []int) { + return file_push_proto_rawDescGZIP(), []int{0} +} + +func (x *Push) GetRoute() string { + if x != nil { + return x.Route + } + return "" +} + +func (x *Push) GetUid() string { + if x != nil { + return x.Uid + } + return "" +} + +func (x *Push) GetData() []byte { + if x != nil { + return x.Data + } + return nil +} + +var File_push_proto protoreflect.FileDescriptor + +var file_push_proto_rawDesc = []byte{ + 0x0a, 0x0a, 0x70, 0x75, 0x73, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x06, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x73, 0x22, 0x42, 0x0a, 0x04, 0x50, 0x75, 0x73, 0x68, 0x12, 0x14, 0x0a, 0x05, + 0x72, 0x6f, 0x75, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x72, 0x6f, 0x75, + 0x74, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x03, 0x75, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x42, 0x3c, 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, + 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, 0x67, 0x61, + 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x73, 0xaa, 0x02, 0x0e, 0x4e, 0x50, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2e, + 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_push_proto_rawDescOnce sync.Once + file_push_proto_rawDescData = file_push_proto_rawDesc +) + +func file_push_proto_rawDescGZIP() []byte { + file_push_proto_rawDescOnce.Do(func() { + file_push_proto_rawDescData = protoimpl.X.CompressGZIP(file_push_proto_rawDescData) + }) + return file_push_proto_rawDescData +} + +var file_push_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_push_proto_goTypes = []interface{}{ + (*Push)(nil), // 0: protos.Push +} +var file_push_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_push_proto_init() } +func file_push_proto_init() { + if File_push_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_push_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Push); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_push_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_push_proto_goTypes, + DependencyIndexes: file_push_proto_depIdxs, + MessageInfos: file_push_proto_msgTypes, + }.Build() + File_push_proto = out.File + file_push_proto_rawDesc = nil + file_push_proto_goTypes = nil + file_push_proto_depIdxs = nil +} diff --git a/pkg/protos/request.pb.go b/pkg/protos/request.pb.go new file mode 100644 index 00000000..a709c9e4 --- /dev/null +++ b/pkg/protos/request.pb.go @@ -0,0 +1,245 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: request.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type RPCType int32 + +const ( + RPCType_Sys RPCType = 0 + RPCType_User RPCType = 1 +) + +// Enum value maps for RPCType. +var ( + RPCType_name = map[int32]string{ + 0: "Sys", + 1: "User", + } + RPCType_value = map[string]int32{ + "Sys": 0, + "User": 1, + } +) + +func (x RPCType) Enum() *RPCType { + p := new(RPCType) + *p = x + return p +} + +func (x RPCType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (RPCType) Descriptor() protoreflect.EnumDescriptor { + return file_request_proto_enumTypes[0].Descriptor() +} + +func (RPCType) Type() protoreflect.EnumType { + return &file_request_proto_enumTypes[0] +} + +func (x RPCType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use RPCType.Descriptor instead. +func (RPCType) EnumDescriptor() ([]byte, []int) { + return file_request_proto_rawDescGZIP(), []int{0} +} + +type Request struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Type RPCType `protobuf:"varint,1,opt,name=type,proto3,enum=protos.RPCType" json:"type,omitempty"` + Session *Session `protobuf:"bytes,2,opt,name=session,proto3" json:"session,omitempty"` + Msg *Msg `protobuf:"bytes,3,opt,name=msg,proto3" json:"msg,omitempty"` + FrontendID string `protobuf:"bytes,4,opt,name=frontendID,proto3" json:"frontendID,omitempty"` + Metadata []byte `protobuf:"bytes,5,opt,name=metadata,proto3" json:"metadata,omitempty"` +} + +func (x *Request) Reset() { + *x = Request{} + if protoimpl.UnsafeEnabled { + mi := &file_request_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Request) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Request) ProtoMessage() {} + +func (x *Request) ProtoReflect() protoreflect.Message { + mi := &file_request_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Request.ProtoReflect.Descriptor instead. +func (*Request) Descriptor() ([]byte, []int) { + return file_request_proto_rawDescGZIP(), []int{0} +} + +func (x *Request) GetType() RPCType { + if x != nil { + return x.Type + } + return RPCType_Sys +} + +func (x *Request) GetSession() *Session { + if x != nil { + return x.Session + } + return nil +} + +func (x *Request) GetMsg() *Msg { + if x != nil { + return x.Msg + } + return nil +} + +func (x *Request) GetFrontendID() string { + if x != nil { + return x.FrontendID + } + return "" +} + +func (x *Request) GetMetadata() []byte { + if x != nil { + return x.Metadata + } + return nil +} + +var File_request_proto protoreflect.FileDescriptor + +var file_request_proto_rawDesc = []byte{ + 0x0a, 0x0d, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x1a, 0x0d, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x09, 0x6d, 0x73, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x22, 0xb4, 0x01, 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x23, 0x0a, + 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x0f, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x52, 0x50, 0x43, 0x54, 0x79, 0x70, 0x65, 0x52, 0x04, 0x74, 0x79, + 0x70, 0x65, 0x12, 0x29, 0x0a, 0x07, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x53, 0x65, 0x73, + 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x07, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1d, 0x0a, + 0x03, 0x6d, 0x73, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x73, 0x2e, 0x4d, 0x73, 0x67, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x12, 0x1e, 0x0a, 0x0a, + 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x49, 0x44, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x0a, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x49, 0x44, 0x12, 0x1a, 0x0a, 0x08, + 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, + 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x2a, 0x1c, 0x0a, 0x07, 0x52, 0x50, 0x43, 0x54, + 0x79, 0x70, 0x65, 0x12, 0x07, 0x0a, 0x03, 0x53, 0x79, 0x73, 0x10, 0x00, 0x12, 0x08, 0x0a, 0x04, + 0x55, 0x73, 0x65, 0x72, 0x10, 0x01, 0x42, 0x3c, 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, + 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, 0x67, 0x61, 0x6d, 0x65, + 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x73, 0xaa, 0x02, 0x0e, 0x4e, 0x50, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2e, 0x50, 0x72, + 0x6f, 0x74, 0x6f, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_request_proto_rawDescOnce sync.Once + file_request_proto_rawDescData = file_request_proto_rawDesc +) + +func file_request_proto_rawDescGZIP() []byte { + file_request_proto_rawDescOnce.Do(func() { + file_request_proto_rawDescData = protoimpl.X.CompressGZIP(file_request_proto_rawDescData) + }) + return file_request_proto_rawDescData +} + +var file_request_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_request_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_request_proto_goTypes = []interface{}{ + (RPCType)(0), // 0: protos.RPCType + (*Request)(nil), // 1: protos.Request + (*Session)(nil), // 2: protos.Session + (*Msg)(nil), // 3: protos.Msg +} +var file_request_proto_depIdxs = []int32{ + 0, // 0: protos.Request.type:type_name -> protos.RPCType + 2, // 1: protos.Request.session:type_name -> protos.Session + 3, // 2: protos.Request.msg:type_name -> protos.Msg + 3, // [3:3] is the sub-list for method output_type + 3, // [3:3] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_request_proto_init() } +func file_request_proto_init() { + if File_request_proto != nil { + return + } + file_session_proto_init() + file_msg_proto_init() + if !protoimpl.UnsafeEnabled { + file_request_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Request); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_request_proto_rawDesc, + NumEnums: 1, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_request_proto_goTypes, + DependencyIndexes: file_request_proto_depIdxs, + EnumInfos: file_request_proto_enumTypes, + MessageInfos: file_request_proto_msgTypes, + }.Build() + File_request_proto = out.File + file_request_proto_rawDesc = nil + file_request_proto_goTypes = nil + file_request_proto_depIdxs = nil +} diff --git a/pkg/protos/response.pb.go b/pkg/protos/response.pb.go new file mode 100644 index 00000000..8cd415c5 --- /dev/null +++ b/pkg/protos/response.pb.go @@ -0,0 +1,158 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: response.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Response struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` + Error *Error `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` +} + +func (x *Response) Reset() { + *x = Response{} + if protoimpl.UnsafeEnabled { + mi := &file_response_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Response) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Response) ProtoMessage() {} + +func (x *Response) ProtoReflect() protoreflect.Message { + mi := &file_response_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Response.ProtoReflect.Descriptor instead. +func (*Response) Descriptor() ([]byte, []int) { + return file_response_proto_rawDescGZIP(), []int{0} +} + +func (x *Response) GetData() []byte { + if x != nil { + return x.Data + } + return nil +} + +func (x *Response) GetError() *Error { + if x != nil { + return x.Error + } + return nil +} + +var File_response_proto protoreflect.FileDescriptor + +var file_response_proto_rawDesc = []byte{ + 0x0a, 0x0e, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x12, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x1a, 0x0b, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x43, 0x0a, 0x08, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, + 0x04, 0x64, 0x61, 0x74, 0x61, 0x12, 0x23, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x45, 0x72, + 0x72, 0x6f, 0x72, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x42, 0x3c, 0x5a, 0x29, 0x67, 0x69, + 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, + 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2f, 0x70, 0x6b, 0x67, + 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0xaa, 0x02, 0x0e, 0x4e, 0x50, 0x69, 0x74, 0x61, 0x79, + 0x61, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_response_proto_rawDescOnce sync.Once + file_response_proto_rawDescData = file_response_proto_rawDesc +) + +func file_response_proto_rawDescGZIP() []byte { + file_response_proto_rawDescOnce.Do(func() { + file_response_proto_rawDescData = protoimpl.X.CompressGZIP(file_response_proto_rawDescData) + }) + return file_response_proto_rawDescData +} + +var file_response_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_response_proto_goTypes = []interface{}{ + (*Response)(nil), // 0: protos.Response + (*Error)(nil), // 1: protos.Error +} +var file_response_proto_depIdxs = []int32{ + 1, // 0: protos.Response.error:type_name -> protos.Error + 1, // [1:1] is the sub-list for method output_type + 1, // [1:1] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_response_proto_init() } +func file_response_proto_init() { + if File_response_proto != nil { + return + } + file_error_proto_init() + if !protoimpl.UnsafeEnabled { + file_response_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Response); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_response_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_response_proto_goTypes, + DependencyIndexes: file_response_proto_depIdxs, + MessageInfos: file_response_proto_msgTypes, + }.Build() + File_response_proto = out.File + file_response_proto_rawDesc = nil + file_response_proto_goTypes = nil + file_response_proto_depIdxs = nil +} diff --git a/pkg/protos/session.pb.go b/pkg/protos/session.pb.go new file mode 100644 index 00000000..7fd4b922 --- /dev/null +++ b/pkg/protos/session.pb.go @@ -0,0 +1,162 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: session.proto + +package protos + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Session struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Uid string `protobuf:"bytes,2,opt,name=uid,proto3" json:"uid,omitempty"` + Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` +} + +func (x *Session) Reset() { + *x = Session{} + if protoimpl.UnsafeEnabled { + mi := &file_session_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Session) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Session) ProtoMessage() {} + +func (x *Session) ProtoReflect() protoreflect.Message { + mi := &file_session_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Session.ProtoReflect.Descriptor instead. +func (*Session) Descriptor() ([]byte, []int) { + return file_session_proto_rawDescGZIP(), []int{0} +} + +func (x *Session) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Session) GetUid() string { + if x != nil { + return x.Uid + } + return "" +} + +func (x *Session) GetData() []byte { + if x != nil { + return x.Data + } + return nil +} + +var File_session_proto protoreflect.FileDescriptor + +var file_session_proto_rawDesc = []byte{ + 0x0a, 0x0d, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x22, 0x3f, 0x0a, 0x07, 0x53, 0x65, 0x73, 0x73, 0x69, + 0x6f, 0x6e, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x02, + 0x69, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x03, 0x75, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x42, 0x3c, 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, + 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, 0x67, 0x61, + 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x73, 0xaa, 0x02, 0x0e, 0x4e, 0x50, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2e, + 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_session_proto_rawDescOnce sync.Once + file_session_proto_rawDescData = file_session_proto_rawDesc +) + +func file_session_proto_rawDescGZIP() []byte { + file_session_proto_rawDescOnce.Do(func() { + file_session_proto_rawDescData = protoimpl.X.CompressGZIP(file_session_proto_rawDescData) + }) + return file_session_proto_rawDescData +} + +var file_session_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_session_proto_goTypes = []interface{}{ + (*Session)(nil), // 0: protos.Session +} +var file_session_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_session_proto_init() } +func file_session_proto_init() { + if File_session_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_session_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Session); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_session_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_session_proto_goTypes, + DependencyIndexes: file_session_proto_depIdxs, + MessageInfos: file_session_proto_msgTypes, + }.Build() + File_session_proto = out.File + file_session_proto_rawDesc = nil + file_session_proto_goTypes = nil + file_session_proto_depIdxs = nil +} diff --git a/pkg/protos/sidecar.pb.go b/pkg/protos/sidecar.pb.go new file mode 100644 index 00000000..abfbe537 --- /dev/null +++ b/pkg/protos/sidecar.pb.go @@ -0,0 +1,928 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: sidecar.proto + +package protos + +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" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type SDEvent_Event int32 + +const ( + SDEvent_ADD SDEvent_Event = 0 + SDEvent_REMOVE SDEvent_Event = 1 +) + +// Enum value maps for SDEvent_Event. +var ( + SDEvent_Event_name = map[int32]string{ + 0: "ADD", + 1: "REMOVE", + } + SDEvent_Event_value = map[string]int32{ + "ADD": 0, + "REMOVE": 1, + } +) + +func (x SDEvent_Event) Enum() *SDEvent_Event { + p := new(SDEvent_Event) + *p = x + return p +} + +func (x SDEvent_Event) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (SDEvent_Event) Descriptor() protoreflect.EnumDescriptor { + return file_sidecar_proto_enumTypes[0].Descriptor() +} + +func (SDEvent_Event) Type() protoreflect.EnumType { + return &file_sidecar_proto_enumTypes[0] +} + +func (x SDEvent_Event) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use SDEvent_Event.Descriptor instead. +func (SDEvent_Event) EnumDescriptor() ([]byte, []int) { + return file_sidecar_proto_rawDescGZIP(), []int{1, 0} +} + +type Server struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Frontend bool `protobuf:"varint,2,opt,name=frontend,proto3" json:"frontend,omitempty"` + Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` + Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` + Hostname string `protobuf:"bytes,5,opt,name=hostname,proto3" json:"hostname,omitempty"` // TODO +} + +func (x *Server) Reset() { + *x = Server{} + if protoimpl.UnsafeEnabled { + mi := &file_sidecar_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Server) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Server) ProtoMessage() {} + +func (x *Server) ProtoReflect() protoreflect.Message { + mi := &file_sidecar_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Server.ProtoReflect.Descriptor instead. +func (*Server) Descriptor() ([]byte, []int) { + return file_sidecar_proto_rawDescGZIP(), []int{0} +} + +func (x *Server) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *Server) GetFrontend() bool { + if x != nil { + return x.Frontend + } + return false +} + +func (x *Server) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *Server) GetMetadata() map[string]string { + if x != nil { + return x.Metadata + } + return nil +} + +func (x *Server) GetHostname() string { + if x != nil { + return x.Hostname + } + return "" +} + +type SDEvent struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Event SDEvent_Event `protobuf:"varint,1,opt,name=event,proto3,enum=protos.SDEvent_Event" json:"event,omitempty"` + Server *Server `protobuf:"bytes,2,opt,name=server,proto3" json:"server,omitempty"` +} + +func (x *SDEvent) Reset() { + *x = SDEvent{} + if protoimpl.UnsafeEnabled { + mi := &file_sidecar_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SDEvent) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SDEvent) ProtoMessage() {} + +func (x *SDEvent) ProtoReflect() protoreflect.Message { + mi := &file_sidecar_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SDEvent.ProtoReflect.Descriptor instead. +func (*SDEvent) Descriptor() ([]byte, []int) { + return file_sidecar_proto_rawDescGZIP(), []int{1} +} + +func (x *SDEvent) GetEvent() SDEvent_Event { + if x != nil { + return x.Event + } + return SDEvent_ADD +} + +func (x *SDEvent) GetServer() *Server { + if x != nil { + return x.Server + } + return nil +} + +type StartPitayaRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Config *Server `protobuf:"bytes,1,opt,name=config,proto3" json:"config,omitempty"` + ShouldCompressMessages bool `protobuf:"varint,2,opt,name=shouldCompressMessages,proto3" json:"shouldCompressMessages,omitempty"` + DebugLog bool `protobuf:"varint,3,opt,name=debugLog,proto3" json:"debugLog,omitempty"` // rpc module +} + +func (x *StartPitayaRequest) Reset() { + *x = StartPitayaRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_sidecar_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *StartPitayaRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StartPitayaRequest) ProtoMessage() {} + +func (x *StartPitayaRequest) ProtoReflect() protoreflect.Message { + mi := &file_sidecar_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use StartPitayaRequest.ProtoReflect.Descriptor instead. +func (*StartPitayaRequest) Descriptor() ([]byte, []int) { + return file_sidecar_proto_rawDescGZIP(), []int{2} +} + +func (x *StartPitayaRequest) GetConfig() *Server { + if x != nil { + return x.Config + } + return nil +} + +func (x *StartPitayaRequest) GetShouldCompressMessages() bool { + if x != nil { + return x.ShouldCompressMessages + } + return false +} + +func (x *StartPitayaRequest) GetDebugLog() bool { + if x != nil { + return x.DebugLog + } + return false +} + +type RequestTo struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ServerID string `protobuf:"bytes,1,opt,name=serverID,proto3" json:"serverID,omitempty"` + Msg *Msg `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg,omitempty"` +} + +func (x *RequestTo) Reset() { + *x = RequestTo{} + if protoimpl.UnsafeEnabled { + mi := &file_sidecar_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RequestTo) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RequestTo) ProtoMessage() {} + +func (x *RequestTo) ProtoReflect() protoreflect.Message { + mi := &file_sidecar_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RequestTo.ProtoReflect.Descriptor instead. +func (*RequestTo) Descriptor() ([]byte, []int) { + return file_sidecar_proto_rawDescGZIP(), []int{3} +} + +func (x *RequestTo) GetServerID() string { + if x != nil { + return x.ServerID + } + return "" +} + +func (x *RequestTo) GetMsg() *Msg { + if x != nil { + return x.Msg + } + return nil +} + +type RPCResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ReqId uint64 `protobuf:"varint,1,opt,name=reqId,proto3" json:"reqId,omitempty"` + Res *Response `protobuf:"bytes,2,opt,name=res,proto3" json:"res,omitempty"` + Err *Error `protobuf:"bytes,3,opt,name=err,proto3" json:"err,omitempty"` +} + +func (x *RPCResponse) Reset() { + *x = RPCResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_sidecar_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RPCResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RPCResponse) ProtoMessage() {} + +func (x *RPCResponse) ProtoReflect() protoreflect.Message { + mi := &file_sidecar_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RPCResponse.ProtoReflect.Descriptor instead. +func (*RPCResponse) Descriptor() ([]byte, []int) { + return file_sidecar_proto_rawDescGZIP(), []int{4} +} + +func (x *RPCResponse) GetReqId() uint64 { + if x != nil { + return x.ReqId + } + return 0 +} + +func (x *RPCResponse) GetRes() *Response { + if x != nil { + return x.Res + } + return nil +} + +func (x *RPCResponse) GetErr() *Error { + if x != nil { + return x.Err + } + return nil +} + +type SidecarRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ReqId uint64 `protobuf:"varint,1,opt,name=reqId,proto3" json:"reqId,omitempty"` + Req *Request `protobuf:"bytes,2,opt,name=req,proto3" json:"req,omitempty"` +} + +func (x *SidecarRequest) Reset() { + *x = SidecarRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_sidecar_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SidecarRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SidecarRequest) ProtoMessage() {} + +func (x *SidecarRequest) ProtoReflect() protoreflect.Message { + mi := &file_sidecar_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SidecarRequest.ProtoReflect.Descriptor instead. +func (*SidecarRequest) Descriptor() ([]byte, []int) { + return file_sidecar_proto_rawDescGZIP(), []int{5} +} + +func (x *SidecarRequest) GetReqId() uint64 { + if x != nil { + return x.ReqId + } + return 0 +} + +func (x *SidecarRequest) GetReq() *Request { + if x != nil { + return x.Req + } + return nil +} + +type PushRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + // TODO I think this field is not needed if we use nats only + FrontendType string `protobuf:"bytes,2,opt,name=frontendType,proto3" json:"frontendType,omitempty"` + Push *Push `protobuf:"bytes,3,opt,name=push,proto3" json:"push,omitempty"` +} + +func (x *PushRequest) Reset() { + *x = PushRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_sidecar_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *PushRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PushRequest) ProtoMessage() {} + +func (x *PushRequest) ProtoReflect() protoreflect.Message { + mi := &file_sidecar_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PushRequest.ProtoReflect.Descriptor instead. +func (*PushRequest) Descriptor() ([]byte, []int) { + return file_sidecar_proto_rawDescGZIP(), []int{6} +} + +func (x *PushRequest) GetFrontendType() string { + if x != nil { + return x.FrontendType + } + return "" +} + +func (x *PushRequest) GetPush() *Push { + if x != nil { + return x.Push + } + return nil +} + +type PushResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + FailedUids []string `protobuf:"bytes,1,rep,name=failedUids,proto3" json:"failedUids,omitempty"` + HasFailed bool `protobuf:"varint,2,opt,name=hasFailed,proto3" json:"hasFailed,omitempty"` +} + +func (x *PushResponse) Reset() { + *x = PushResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_sidecar_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *PushResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PushResponse) ProtoMessage() {} + +func (x *PushResponse) ProtoReflect() protoreflect.Message { + mi := &file_sidecar_proto_msgTypes[7] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PushResponse.ProtoReflect.Descriptor instead. +func (*PushResponse) Descriptor() ([]byte, []int) { + return file_sidecar_proto_rawDescGZIP(), []int{7} +} + +func (x *PushResponse) GetFailedUids() []string { + if x != nil { + return x.FailedUids + } + return nil +} + +func (x *PushResponse) GetHasFailed() bool { + if x != nil { + return x.HasFailed + } + return false +} + +type KickRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + FrontendType string `protobuf:"bytes,2,opt,name=frontendType,proto3" json:"frontendType,omitempty"` + Kick *KickMsg `protobuf:"bytes,3,opt,name=kick,proto3" json:"kick,omitempty"` +} + +func (x *KickRequest) Reset() { + *x = KickRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_sidecar_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *KickRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*KickRequest) ProtoMessage() {} + +func (x *KickRequest) ProtoReflect() protoreflect.Message { + mi := &file_sidecar_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use KickRequest.ProtoReflect.Descriptor instead. +func (*KickRequest) Descriptor() ([]byte, []int) { + return file_sidecar_proto_rawDescGZIP(), []int{8} +} + +func (x *KickRequest) GetFrontendType() string { + if x != nil { + return x.FrontendType + } + return "" +} + +func (x *KickRequest) GetKick() *KickMsg { + if x != nil { + return x.Kick + } + return nil +} + +var File_sidecar_proto protoreflect.FileDescriptor + +var file_sidecar_proto_rawDesc = []byte{ + 0x0a, 0x0d, 0x73, 0x69, 0x64, 0x65, 0x63, 0x61, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x1a, 0x0b, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x0a, 0x70, 0x75, 0x73, 0x68, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x1a, 0x0a, 0x6b, 0x69, 0x63, 0x6b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x09, 0x6d, 0x73, + 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x0e, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x0d, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 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, 0x22, 0xdb, 0x01, 0x0a, 0x06, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x12, 0x0e, + 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x1a, + 0x0a, 0x08, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, + 0x52, 0x08, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, + 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x38, + 0x0a, 0x08, 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x1c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, + 0x2e, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x08, + 0x6d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x1a, 0x0a, 0x08, 0x68, 0x6f, 0x73, 0x74, + 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x68, 0x6f, 0x73, 0x74, + 0x6e, 0x61, 0x6d, 0x65, 0x1a, 0x3b, 0x0a, 0x0d, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, + 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, + 0x01, 0x22, 0x7c, 0x0a, 0x07, 0x53, 0x44, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x2b, 0x0a, 0x05, + 0x65, 0x76, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x15, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x53, 0x44, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x2e, 0x45, 0x76, 0x65, + 0x6e, 0x74, 0x52, 0x05, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x26, 0x0a, 0x06, 0x73, 0x65, 0x72, + 0x76, 0x65, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x73, 0x2e, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, + 0x72, 0x22, 0x1c, 0x0a, 0x05, 0x45, 0x76, 0x65, 0x6e, 0x74, 0x12, 0x07, 0x0a, 0x03, 0x41, 0x44, + 0x44, 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x52, 0x45, 0x4d, 0x4f, 0x56, 0x45, 0x10, 0x01, 0x22, + 0x90, 0x01, 0x0a, 0x12, 0x53, 0x74, 0x61, 0x72, 0x74, 0x50, 0x69, 0x74, 0x61, 0x79, 0x61, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x26, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, + 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x36, + 0x0a, 0x16, 0x73, 0x68, 0x6f, 0x75, 0x6c, 0x64, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, + 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x16, + 0x73, 0x68, 0x6f, 0x75, 0x6c, 0x64, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73, 0x73, 0x4d, 0x65, + 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x62, 0x75, 0x67, 0x4c, + 0x6f, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x64, 0x65, 0x62, 0x75, 0x67, 0x4c, + 0x6f, 0x67, 0x22, 0x46, 0x0a, 0x09, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x54, 0x6f, 0x12, + 0x1a, 0x0a, 0x08, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x08, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x49, 0x44, 0x12, 0x1d, 0x0a, 0x03, 0x6d, + 0x73, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x73, 0x2e, 0x4d, 0x73, 0x67, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x22, 0x68, 0x0a, 0x0b, 0x52, 0x50, + 0x43, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x72, 0x65, 0x71, + 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x72, 0x65, 0x71, 0x49, 0x64, 0x12, + 0x22, 0x0a, 0x03, 0x72, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x03, + 0x72, 0x65, 0x73, 0x12, 0x1f, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x0d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, + 0x03, 0x65, 0x72, 0x72, 0x22, 0x49, 0x0a, 0x0e, 0x53, 0x69, 0x64, 0x65, 0x63, 0x61, 0x72, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x72, 0x65, 0x71, 0x49, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x72, 0x65, 0x71, 0x49, 0x64, 0x12, 0x21, 0x0a, 0x03, + 0x72, 0x65, 0x71, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x73, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x52, 0x03, 0x72, 0x65, 0x71, 0x22, + 0x53, 0x0a, 0x0b, 0x50, 0x75, 0x73, 0x68, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x22, + 0x0a, 0x0c, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x54, 0x79, 0x70, 0x65, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x54, 0x79, + 0x70, 0x65, 0x12, 0x20, 0x0a, 0x04, 0x70, 0x75, 0x73, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x0c, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x50, 0x75, 0x73, 0x68, 0x52, 0x04, + 0x70, 0x75, 0x73, 0x68, 0x22, 0x4c, 0x0a, 0x0c, 0x50, 0x75, 0x73, 0x68, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x66, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x55, 0x69, + 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0a, 0x66, 0x61, 0x69, 0x6c, 0x65, 0x64, + 0x55, 0x69, 0x64, 0x73, 0x12, 0x1c, 0x0a, 0x09, 0x68, 0x61, 0x73, 0x46, 0x61, 0x69, 0x6c, 0x65, + 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x09, 0x68, 0x61, 0x73, 0x46, 0x61, 0x69, 0x6c, + 0x65, 0x64, 0x22, 0x56, 0x0a, 0x0b, 0x4b, 0x69, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x12, 0x22, 0x0a, 0x0c, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x64, 0x54, 0x79, 0x70, + 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x66, 0x72, 0x6f, 0x6e, 0x74, 0x65, 0x6e, + 0x64, 0x54, 0x79, 0x70, 0x65, 0x12, 0x23, 0x0a, 0x04, 0x6b, 0x69, 0x63, 0x6b, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x4b, 0x69, 0x63, + 0x6b, 0x4d, 0x73, 0x67, 0x52, 0x04, 0x6b, 0x69, 0x63, 0x6b, 0x32, 0xf5, 0x03, 0x0a, 0x07, 0x53, + 0x69, 0x64, 0x65, 0x63, 0x61, 0x72, 0x12, 0x2b, 0x0a, 0x09, 0x47, 0x65, 0x74, 0x53, 0x65, 0x72, + 0x76, 0x65, 0x72, 0x12, 0x0e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x53, 0x65, 0x72, + 0x76, 0x65, 0x72, 0x1a, 0x0e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x53, 0x65, 0x72, + 0x76, 0x65, 0x72, 0x12, 0x3b, 0x0a, 0x09, 0x48, 0x65, 0x61, 0x72, 0x74, 0x62, 0x65, 0x61, 0x74, + 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, + 0x12, 0x3c, 0x0a, 0x09, 0x4c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x52, 0x50, 0x43, 0x12, 0x13, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x52, 0x50, 0x43, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x1a, 0x16, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x53, 0x69, 0x64, 0x65, + 0x63, 0x61, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x28, 0x01, 0x30, 0x01, 0x12, 0x35, + 0x0a, 0x08, 0x4c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x53, 0x44, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, + 0x74, 0x79, 0x1a, 0x0f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x53, 0x44, 0x45, 0x76, + 0x65, 0x6e, 0x74, 0x30, 0x01, 0x12, 0x2e, 0x0a, 0x07, 0x53, 0x65, 0x6e, 0x64, 0x52, 0x50, 0x43, + 0x12, 0x11, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x54, 0x6f, 0x1a, 0x10, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x53, 0x65, 0x6e, 0x64, 0x50, 0x75, 0x73, + 0x68, 0x12, 0x13, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x50, 0x75, 0x73, 0x68, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, + 0x50, 0x75, 0x73, 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x08, + 0x53, 0x65, 0x6e, 0x64, 0x4b, 0x69, 0x63, 0x6b, 0x12, 0x13, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x73, 0x2e, 0x4b, 0x69, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x50, 0x75, 0x73, 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x38, 0x0a, 0x0b, 0x53, 0x74, 0x61, 0x72, 0x74, 0x50, 0x69, 0x74, 0x61, + 0x79, 0x61, 0x12, 0x1a, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x53, 0x74, 0x61, 0x72, + 0x74, 0x50, 0x69, 0x74, 0x61, 0x79, 0x61, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x0d, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x33, 0x0a, + 0x0a, 0x53, 0x74, 0x6f, 0x70, 0x50, 0x69, 0x74, 0x61, 0x79, 0x61, 0x12, 0x16, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, + 0x70, 0x74, 0x79, 0x1a, 0x0d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2e, 0x45, 0x72, 0x72, + 0x6f, 0x72, 0x42, 0x3c, 0x5a, 0x29, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, + 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, + 0x74, 0x61, 0x79, 0x61, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0xaa, + 0x02, 0x0e, 0x4e, 0x50, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2e, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, + 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_sidecar_proto_rawDescOnce sync.Once + file_sidecar_proto_rawDescData = file_sidecar_proto_rawDesc +) + +func file_sidecar_proto_rawDescGZIP() []byte { + file_sidecar_proto_rawDescOnce.Do(func() { + file_sidecar_proto_rawDescData = protoimpl.X.CompressGZIP(file_sidecar_proto_rawDescData) + }) + return file_sidecar_proto_rawDescData +} + +var file_sidecar_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_sidecar_proto_msgTypes = make([]protoimpl.MessageInfo, 10) +var file_sidecar_proto_goTypes = []interface{}{ + (SDEvent_Event)(0), // 0: protos.SDEvent.Event + (*Server)(nil), // 1: protos.Server + (*SDEvent)(nil), // 2: protos.SDEvent + (*StartPitayaRequest)(nil), // 3: protos.StartPitayaRequest + (*RequestTo)(nil), // 4: protos.RequestTo + (*RPCResponse)(nil), // 5: protos.RPCResponse + (*SidecarRequest)(nil), // 6: protos.SidecarRequest + (*PushRequest)(nil), // 7: protos.PushRequest + (*PushResponse)(nil), // 8: protos.PushResponse + (*KickRequest)(nil), // 9: protos.KickRequest + nil, // 10: protos.Server.MetadataEntry + (*Msg)(nil), // 11: protos.Msg + (*Response)(nil), // 12: protos.Response + (*Error)(nil), // 13: protos.Error + (*Request)(nil), // 14: protos.Request + (*Push)(nil), // 15: protos.Push + (*KickMsg)(nil), // 16: protos.KickMsg + (*emptypb.Empty)(nil), // 17: google.protobuf.Empty +} +var file_sidecar_proto_depIdxs = []int32{ + 10, // 0: protos.Server.metadata:type_name -> protos.Server.MetadataEntry + 0, // 1: protos.SDEvent.event:type_name -> protos.SDEvent.Event + 1, // 2: protos.SDEvent.server:type_name -> protos.Server + 1, // 3: protos.StartPitayaRequest.config:type_name -> protos.Server + 11, // 4: protos.RequestTo.msg:type_name -> protos.Msg + 12, // 5: protos.RPCResponse.res:type_name -> protos.Response + 13, // 6: protos.RPCResponse.err:type_name -> protos.Error + 14, // 7: protos.SidecarRequest.req:type_name -> protos.Request + 15, // 8: protos.PushRequest.push:type_name -> protos.Push + 16, // 9: protos.KickRequest.kick:type_name -> protos.KickMsg + 1, // 10: protos.Sidecar.GetServer:input_type -> protos.Server + 17, // 11: protos.Sidecar.Heartbeat:input_type -> google.protobuf.Empty + 5, // 12: protos.Sidecar.ListenRPC:input_type -> protos.RPCResponse + 17, // 13: protos.Sidecar.ListenSD:input_type -> google.protobuf.Empty + 4, // 14: protos.Sidecar.SendRPC:input_type -> protos.RequestTo + 7, // 15: protos.Sidecar.SendPush:input_type -> protos.PushRequest + 9, // 16: protos.Sidecar.SendKick:input_type -> protos.KickRequest + 3, // 17: protos.Sidecar.StartPitaya:input_type -> protos.StartPitayaRequest + 17, // 18: protos.Sidecar.StopPitaya:input_type -> google.protobuf.Empty + 1, // 19: protos.Sidecar.GetServer:output_type -> protos.Server + 17, // 20: protos.Sidecar.Heartbeat:output_type -> google.protobuf.Empty + 6, // 21: protos.Sidecar.ListenRPC:output_type -> protos.SidecarRequest + 2, // 22: protos.Sidecar.ListenSD:output_type -> protos.SDEvent + 12, // 23: protos.Sidecar.SendRPC:output_type -> protos.Response + 8, // 24: protos.Sidecar.SendPush:output_type -> protos.PushResponse + 8, // 25: protos.Sidecar.SendKick:output_type -> protos.PushResponse + 13, // 26: protos.Sidecar.StartPitaya:output_type -> protos.Error + 13, // 27: protos.Sidecar.StopPitaya:output_type -> protos.Error + 19, // [19:28] is the sub-list for method output_type + 10, // [10:19] is the sub-list for method input_type + 10, // [10:10] is the sub-list for extension type_name + 10, // [10:10] is the sub-list for extension extendee + 0, // [0:10] is the sub-list for field type_name +} + +func init() { file_sidecar_proto_init() } +func file_sidecar_proto_init() { + if File_sidecar_proto != nil { + return + } + file_error_proto_init() + file_push_proto_init() + file_kick_proto_init() + file_msg_proto_init() + file_response_proto_init() + file_request_proto_init() + if !protoimpl.UnsafeEnabled { + file_sidecar_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Server); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sidecar_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SDEvent); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sidecar_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*StartPitayaRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sidecar_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RequestTo); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sidecar_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RPCResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sidecar_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SidecarRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sidecar_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*PushRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sidecar_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*PushResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sidecar_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*KickRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_sidecar_proto_rawDesc, + NumEnums: 1, + NumMessages: 10, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_sidecar_proto_goTypes, + DependencyIndexes: file_sidecar_proto_depIdxs, + EnumInfos: file_sidecar_proto_enumTypes, + MessageInfos: file_sidecar_proto_msgTypes, + }.Build() + File_sidecar_proto = out.File + file_sidecar_proto_rawDesc = nil + file_sidecar_proto_goTypes = nil + file_sidecar_proto_depIdxs = nil +} diff --git a/pkg/protos/sidecar_grpc.pb.go b/pkg/protos/sidecar_grpc.pb.go new file mode 100644 index 00000000..0bce3322 --- /dev/null +++ b/pkg/protos/sidecar_grpc.pb.go @@ -0,0 +1,448 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. + +package protos + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + emptypb "google.golang.org/protobuf/types/known/emptypb" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +// SidecarClient is the client API for Sidecar service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type SidecarClient interface { + GetServer(ctx context.Context, in *Server, opts ...grpc.CallOption) (*Server, error) + Heartbeat(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error) + ListenRPC(ctx context.Context, opts ...grpc.CallOption) (Sidecar_ListenRPCClient, error) + ListenSD(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (Sidecar_ListenSDClient, error) + SendRPC(ctx context.Context, in *RequestTo, opts ...grpc.CallOption) (*Response, error) + SendPush(ctx context.Context, in *PushRequest, opts ...grpc.CallOption) (*PushResponse, error) + SendKick(ctx context.Context, in *KickRequest, opts ...grpc.CallOption) (*PushResponse, error) + StartPitaya(ctx context.Context, in *StartPitayaRequest, opts ...grpc.CallOption) (*Error, error) + StopPitaya(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*Error, error) +} + +type sidecarClient struct { + cc grpc.ClientConnInterface +} + +func NewSidecarClient(cc grpc.ClientConnInterface) SidecarClient { + return &sidecarClient{cc} +} + +func (c *sidecarClient) GetServer(ctx context.Context, in *Server, opts ...grpc.CallOption) (*Server, error) { + out := new(Server) + err := c.cc.Invoke(ctx, "/protos.Sidecar/GetServer", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sidecarClient) Heartbeat(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error) { + out := new(emptypb.Empty) + err := c.cc.Invoke(ctx, "/protos.Sidecar/Heartbeat", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sidecarClient) ListenRPC(ctx context.Context, opts ...grpc.CallOption) (Sidecar_ListenRPCClient, error) { + stream, err := c.cc.NewStream(ctx, &Sidecar_ServiceDesc.Streams[0], "/protos.Sidecar/ListenRPC", opts...) + if err != nil { + return nil, err + } + x := &sidecarListenRPCClient{stream} + return x, nil +} + +type Sidecar_ListenRPCClient interface { + Send(*RPCResponse) error + Recv() (*SidecarRequest, error) + grpc.ClientStream +} + +type sidecarListenRPCClient struct { + grpc.ClientStream +} + +func (x *sidecarListenRPCClient) Send(m *RPCResponse) error { + return x.ClientStream.SendMsg(m) +} + +func (x *sidecarListenRPCClient) Recv() (*SidecarRequest, error) { + m := new(SidecarRequest) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (c *sidecarClient) ListenSD(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (Sidecar_ListenSDClient, error) { + stream, err := c.cc.NewStream(ctx, &Sidecar_ServiceDesc.Streams[1], "/protos.Sidecar/ListenSD", opts...) + if err != nil { + return nil, err + } + x := &sidecarListenSDClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type Sidecar_ListenSDClient interface { + Recv() (*SDEvent, error) + grpc.ClientStream +} + +type sidecarListenSDClient struct { + grpc.ClientStream +} + +func (x *sidecarListenSDClient) Recv() (*SDEvent, error) { + m := new(SDEvent) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (c *sidecarClient) SendRPC(ctx context.Context, in *RequestTo, opts ...grpc.CallOption) (*Response, error) { + out := new(Response) + err := c.cc.Invoke(ctx, "/protos.Sidecar/SendRPC", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sidecarClient) SendPush(ctx context.Context, in *PushRequest, opts ...grpc.CallOption) (*PushResponse, error) { + out := new(PushResponse) + err := c.cc.Invoke(ctx, "/protos.Sidecar/SendPush", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sidecarClient) SendKick(ctx context.Context, in *KickRequest, opts ...grpc.CallOption) (*PushResponse, error) { + out := new(PushResponse) + err := c.cc.Invoke(ctx, "/protos.Sidecar/SendKick", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sidecarClient) StartPitaya(ctx context.Context, in *StartPitayaRequest, opts ...grpc.CallOption) (*Error, error) { + out := new(Error) + err := c.cc.Invoke(ctx, "/protos.Sidecar/StartPitaya", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sidecarClient) StopPitaya(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*Error, error) { + out := new(Error) + err := c.cc.Invoke(ctx, "/protos.Sidecar/StopPitaya", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// SidecarServer is the server API for Sidecar service. +// All implementations should embed UnimplementedSidecarServer +// for forward compatibility +type SidecarServer interface { + GetServer(context.Context, *Server) (*Server, error) + Heartbeat(context.Context, *emptypb.Empty) (*emptypb.Empty, error) + ListenRPC(Sidecar_ListenRPCServer) error + ListenSD(*emptypb.Empty, Sidecar_ListenSDServer) error + SendRPC(context.Context, *RequestTo) (*Response, error) + SendPush(context.Context, *PushRequest) (*PushResponse, error) + SendKick(context.Context, *KickRequest) (*PushResponse, error) + StartPitaya(context.Context, *StartPitayaRequest) (*Error, error) + StopPitaya(context.Context, *emptypb.Empty) (*Error, error) +} + +// UnimplementedSidecarServer should be embedded to have forward compatible implementations. +type UnimplementedSidecarServer struct { +} + +func (UnimplementedSidecarServer) GetServer(context.Context, *Server) (*Server, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetServer not implemented") +} +func (UnimplementedSidecarServer) Heartbeat(context.Context, *emptypb.Empty) (*emptypb.Empty, error) { + return nil, status.Errorf(codes.Unimplemented, "method Heartbeat not implemented") +} +func (UnimplementedSidecarServer) ListenRPC(Sidecar_ListenRPCServer) error { + return status.Errorf(codes.Unimplemented, "method ListenRPC not implemented") +} +func (UnimplementedSidecarServer) ListenSD(*emptypb.Empty, Sidecar_ListenSDServer) error { + return status.Errorf(codes.Unimplemented, "method ListenSD not implemented") +} +func (UnimplementedSidecarServer) SendRPC(context.Context, *RequestTo) (*Response, error) { + return nil, status.Errorf(codes.Unimplemented, "method SendRPC not implemented") +} +func (UnimplementedSidecarServer) SendPush(context.Context, *PushRequest) (*PushResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SendPush not implemented") +} +func (UnimplementedSidecarServer) SendKick(context.Context, *KickRequest) (*PushResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SendKick not implemented") +} +func (UnimplementedSidecarServer) StartPitaya(context.Context, *StartPitayaRequest) (*Error, error) { + return nil, status.Errorf(codes.Unimplemented, "method StartPitaya not implemented") +} +func (UnimplementedSidecarServer) StopPitaya(context.Context, *emptypb.Empty) (*Error, error) { + return nil, status.Errorf(codes.Unimplemented, "method StopPitaya not implemented") +} + +// UnsafeSidecarServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to SidecarServer will +// result in compilation errors. +type UnsafeSidecarServer interface { + mustEmbedUnimplementedSidecarServer() +} + +func RegisterSidecarServer(s grpc.ServiceRegistrar, srv SidecarServer) { + s.RegisterService(&Sidecar_ServiceDesc, srv) +} + +func _Sidecar_GetServer_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Server) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SidecarServer).GetServer(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/protos.Sidecar/GetServer", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SidecarServer).GetServer(ctx, req.(*Server)) + } + return interceptor(ctx, in, info, handler) +} + +func _Sidecar_Heartbeat_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(emptypb.Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SidecarServer).Heartbeat(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/protos.Sidecar/Heartbeat", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SidecarServer).Heartbeat(ctx, req.(*emptypb.Empty)) + } + return interceptor(ctx, in, info, handler) +} + +func _Sidecar_ListenRPC_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(SidecarServer).ListenRPC(&sidecarListenRPCServer{stream}) +} + +type Sidecar_ListenRPCServer interface { + Send(*SidecarRequest) error + Recv() (*RPCResponse, error) + grpc.ServerStream +} + +type sidecarListenRPCServer struct { + grpc.ServerStream +} + +func (x *sidecarListenRPCServer) Send(m *SidecarRequest) error { + return x.ServerStream.SendMsg(m) +} + +func (x *sidecarListenRPCServer) Recv() (*RPCResponse, error) { + m := new(RPCResponse) + if err := x.ServerStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func _Sidecar_ListenSD_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(emptypb.Empty) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(SidecarServer).ListenSD(m, &sidecarListenSDServer{stream}) +} + +type Sidecar_ListenSDServer interface { + Send(*SDEvent) error + grpc.ServerStream +} + +type sidecarListenSDServer struct { + grpc.ServerStream +} + +func (x *sidecarListenSDServer) Send(m *SDEvent) error { + return x.ServerStream.SendMsg(m) +} + +func _Sidecar_SendRPC_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RequestTo) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SidecarServer).SendRPC(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/protos.Sidecar/SendRPC", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SidecarServer).SendRPC(ctx, req.(*RequestTo)) + } + return interceptor(ctx, in, info, handler) +} + +func _Sidecar_SendPush_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(PushRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SidecarServer).SendPush(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/protos.Sidecar/SendPush", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SidecarServer).SendPush(ctx, req.(*PushRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Sidecar_SendKick_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(KickRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SidecarServer).SendKick(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/protos.Sidecar/SendKick", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SidecarServer).SendKick(ctx, req.(*KickRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Sidecar_StartPitaya_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(StartPitayaRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SidecarServer).StartPitaya(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/protos.Sidecar/StartPitaya", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SidecarServer).StartPitaya(ctx, req.(*StartPitayaRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Sidecar_StopPitaya_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(emptypb.Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SidecarServer).StopPitaya(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/protos.Sidecar/StopPitaya", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SidecarServer).StopPitaya(ctx, req.(*emptypb.Empty)) + } + return interceptor(ctx, in, info, handler) +} + +// Sidecar_ServiceDesc is the grpc.ServiceDesc for Sidecar service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Sidecar_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "protos.Sidecar", + HandlerType: (*SidecarServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetServer", + Handler: _Sidecar_GetServer_Handler, + }, + { + MethodName: "Heartbeat", + Handler: _Sidecar_Heartbeat_Handler, + }, + { + MethodName: "SendRPC", + Handler: _Sidecar_SendRPC_Handler, + }, + { + MethodName: "SendPush", + Handler: _Sidecar_SendPush_Handler, + }, + { + MethodName: "SendKick", + Handler: _Sidecar_SendKick_Handler, + }, + { + MethodName: "StartPitaya", + Handler: _Sidecar_StartPitaya_Handler, + }, + { + MethodName: "StopPitaya", + Handler: _Sidecar_StopPitaya_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "ListenRPC", + Handler: _Sidecar_ListenRPC_Handler, + ServerStreams: true, + ClientStreams: true, + }, + { + StreamName: "ListenSD", + Handler: _Sidecar_ListenSD_Handler, + ServerStreams: true, + }, + }, + Metadata: "sidecar.proto", +} diff --git a/pkg/protos/test/somestruct.pb.go b/pkg/protos/test/somestruct.pb.go new file mode 100644 index 00000000..89919410 --- /dev/null +++ b/pkg/protos/test/somestruct.pb.go @@ -0,0 +1,152 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: somestruct.proto + +package test + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type SomeStruct struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + A int32 `protobuf:"varint,1,opt,name=A,proto3" json:"A,omitempty"` + B string `protobuf:"bytes,2,opt,name=B,proto3" json:"B,omitempty"` +} + +func (x *SomeStruct) Reset() { + *x = SomeStruct{} + if protoimpl.UnsafeEnabled { + mi := &file_somestruct_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SomeStruct) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SomeStruct) ProtoMessage() {} + +func (x *SomeStruct) ProtoReflect() protoreflect.Message { + mi := &file_somestruct_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SomeStruct.ProtoReflect.Descriptor instead. +func (*SomeStruct) Descriptor() ([]byte, []int) { + return file_somestruct_proto_rawDescGZIP(), []int{0} +} + +func (x *SomeStruct) GetA() int32 { + if x != nil { + return x.A + } + return 0 +} + +func (x *SomeStruct) GetB() string { + if x != nil { + return x.B + } + return "" +} + +var File_somestruct_proto protoreflect.FileDescriptor + +var file_somestruct_proto_rawDesc = []byte{ + 0x0a, 0x10, 0x73, 0x6f, 0x6d, 0x65, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x12, 0x04, 0x74, 0x65, 0x73, 0x74, 0x22, 0x28, 0x0a, 0x0a, 0x53, 0x6f, 0x6d, 0x65, + 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x12, 0x0c, 0x0a, 0x01, 0x41, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x05, 0x52, 0x01, 0x41, 0x12, 0x0c, 0x0a, 0x01, 0x42, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x01, 0x42, 0x42, 0x30, 0x5a, 0x2e, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, + 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, + 0x74, 0x61, 0x79, 0x61, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2f, + 0x74, 0x65, 0x73, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_somestruct_proto_rawDescOnce sync.Once + file_somestruct_proto_rawDescData = file_somestruct_proto_rawDesc +) + +func file_somestruct_proto_rawDescGZIP() []byte { + file_somestruct_proto_rawDescOnce.Do(func() { + file_somestruct_proto_rawDescData = protoimpl.X.CompressGZIP(file_somestruct_proto_rawDescData) + }) + return file_somestruct_proto_rawDescData +} + +var file_somestruct_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_somestruct_proto_goTypes = []interface{}{ + (*SomeStruct)(nil), // 0: test.SomeStruct +} +var file_somestruct_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_somestruct_proto_init() } +func file_somestruct_proto_init() { + if File_somestruct_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_somestruct_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SomeStruct); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_somestruct_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_somestruct_proto_goTypes, + DependencyIndexes: file_somestruct_proto_depIdxs, + MessageInfos: file_somestruct_proto_msgTypes, + }.Build() + File_somestruct_proto = out.File + file_somestruct_proto_rawDesc = nil + file_somestruct_proto_goTypes = nil + file_somestruct_proto_depIdxs = nil +} diff --git a/pkg/protos/test/testrequest.pb.go b/pkg/protos/test/testrequest.pb.go new file mode 100644 index 00000000..9f9420c9 --- /dev/null +++ b/pkg/protos/test/testrequest.pb.go @@ -0,0 +1,144 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: testrequest.proto + +package test + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type TestRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Msg string `protobuf:"bytes,1,opt,name=msg,proto3" json:"msg,omitempty"` +} + +func (x *TestRequest) Reset() { + *x = TestRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_testrequest_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestRequest) ProtoMessage() {} + +func (x *TestRequest) ProtoReflect() protoreflect.Message { + mi := &file_testrequest_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TestRequest.ProtoReflect.Descriptor instead. +func (*TestRequest) Descriptor() ([]byte, []int) { + return file_testrequest_proto_rawDescGZIP(), []int{0} +} + +func (x *TestRequest) GetMsg() string { + if x != nil { + return x.Msg + } + return "" +} + +var File_testrequest_proto protoreflect.FileDescriptor + +var file_testrequest_proto_rawDesc = []byte{ + 0x0a, 0x11, 0x74, 0x65, 0x73, 0x74, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x12, 0x04, 0x74, 0x65, 0x73, 0x74, 0x22, 0x1f, 0x0a, 0x0b, 0x54, 0x65, 0x73, + 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x6d, 0x73, 0x67, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x42, 0x30, 0x5a, 0x2e, 0x67, 0x69, + 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, + 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, 0x79, 0x61, 0x2f, 0x70, 0x6b, 0x67, + 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x62, 0x06, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_testrequest_proto_rawDescOnce sync.Once + file_testrequest_proto_rawDescData = file_testrequest_proto_rawDesc +) + +func file_testrequest_proto_rawDescGZIP() []byte { + file_testrequest_proto_rawDescOnce.Do(func() { + file_testrequest_proto_rawDescData = protoimpl.X.CompressGZIP(file_testrequest_proto_rawDescData) + }) + return file_testrequest_proto_rawDescData +} + +var file_testrequest_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_testrequest_proto_goTypes = []interface{}{ + (*TestRequest)(nil), // 0: test.TestRequest +} +var file_testrequest_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_testrequest_proto_init() } +func file_testrequest_proto_init() { + if File_testrequest_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_testrequest_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_testrequest_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_testrequest_proto_goTypes, + DependencyIndexes: file_testrequest_proto_depIdxs, + MessageInfos: file_testrequest_proto_msgTypes, + }.Build() + File_testrequest_proto = out.File + file_testrequest_proto_rawDesc = nil + file_testrequest_proto_goTypes = nil + file_testrequest_proto_depIdxs = nil +} diff --git a/pkg/protos/test/testresponse.pb.go b/pkg/protos/test/testresponse.pb.go new file mode 100644 index 00000000..e9321435 --- /dev/null +++ b/pkg/protos/test/testresponse.pb.go @@ -0,0 +1,153 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v3.17.3 +// source: testresponse.proto + +package test + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type TestResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Msg string `protobuf:"bytes,2,opt,name=msg,proto3" json:"msg,omitempty"` +} + +func (x *TestResponse) Reset() { + *x = TestResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_testresponse_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TestResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TestResponse) ProtoMessage() {} + +func (x *TestResponse) ProtoReflect() protoreflect.Message { + mi := &file_testresponse_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TestResponse.ProtoReflect.Descriptor instead. +func (*TestResponse) Descriptor() ([]byte, []int) { + return file_testresponse_proto_rawDescGZIP(), []int{0} +} + +func (x *TestResponse) GetCode() int32 { + if x != nil { + return x.Code + } + return 0 +} + +func (x *TestResponse) GetMsg() string { + if x != nil { + return x.Msg + } + return "" +} + +var File_testresponse_proto protoreflect.FileDescriptor + +var file_testresponse_proto_rawDesc = []byte{ + 0x0a, 0x12, 0x74, 0x65, 0x73, 0x74, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x04, 0x74, 0x65, 0x73, 0x74, 0x22, 0x34, 0x0a, 0x0c, 0x54, 0x65, + 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, + 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x10, + 0x0a, 0x03, 0x6d, 0x73, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6d, 0x73, 0x67, + 0x42, 0x30, 0x5a, 0x2e, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, + 0x6f, 0x70, 0x66, 0x72, 0x65, 0x65, 0x67, 0x61, 0x6d, 0x65, 0x73, 0x2f, 0x70, 0x69, 0x74, 0x61, + 0x79, 0x61, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x2f, 0x74, 0x65, + 0x73, 0x74, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_testresponse_proto_rawDescOnce sync.Once + file_testresponse_proto_rawDescData = file_testresponse_proto_rawDesc +) + +func file_testresponse_proto_rawDescGZIP() []byte { + file_testresponse_proto_rawDescOnce.Do(func() { + file_testresponse_proto_rawDescData = protoimpl.X.CompressGZIP(file_testresponse_proto_rawDescData) + }) + return file_testresponse_proto_rawDescData +} + +var file_testresponse_proto_msgTypes = make([]protoimpl.MessageInfo, 1) +var file_testresponse_proto_goTypes = []interface{}{ + (*TestResponse)(nil), // 0: test.TestResponse +} +var file_testresponse_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_testresponse_proto_init() } +func file_testresponse_proto_init() { + if File_testresponse_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_testresponse_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TestResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_testresponse_proto_rawDesc, + NumEnums: 0, + NumMessages: 1, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_testresponse_proto_goTypes, + DependencyIndexes: file_testresponse_proto_depIdxs, + MessageInfos: file_testresponse_proto_msgTypes, + }.Build() + File_testresponse_proto = out.File + file_testresponse_proto_rawDesc = nil + file_testresponse_proto_goTypes = nil + file_testresponse_proto_depIdxs = nil +} diff --git a/push.go b/pkg/push.go similarity index 88% rename from push.go rename to pkg/push.go index e9049dd9..91384f64 100644 --- a/push.go +++ b/pkg/push.go @@ -18,14 +18,14 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/util" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/constants" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/util" ) // SendPushToUsers sends a message to the given list of users @@ -43,6 +43,8 @@ func (app *App) SendPushToUsers(route string, v interface{}, uids []string, fron logger.Log.Debugf("Type=PushToUsers Route=%s, Data=%+v, SvType=%s, #Users=%d", route, v, frontendType, len(uids)) + // TODO we could use concurrency for sending the pushes here, not see why not + // doing it for _, uid := range uids { if s := app.sessionPool.GetSessionByUID(uid); s != nil && app.server.Type == frontendType { if err := s.Push(route, data); err != nil { diff --git a/push_test.go b/pkg/push_test.go similarity index 93% rename from push_test.go rename to pkg/push_test.go index 7a433fa9..ea79dd41 100644 --- a/push_test.go +++ b/pkg/push_test.go @@ -18,21 +18,21 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "errors" + clustermocks "github.com/topfreegames/pitaya/v3/pkg/cluster/mocks" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/stretchr/testify/assert" - clustermocks "github.com/topfreegames/pitaya/v2/cluster/mocks" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/protos" - serializemocks "github.com/topfreegames/pitaya/v2/serialize/mocks" - sessionmocks "github.com/topfreegames/pitaya/v2/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/protos" + serializemocks "github.com/topfreegames/pitaya/v3/pkg/serialize/mocks" + sessionmocks "github.com/topfreegames/pitaya/v3/pkg/session/mocks" ) type someStruct struct { diff --git a/remote/sys.go b/pkg/remote/sys.go similarity index 92% rename from remote/sys.go rename to pkg/remote/sys.go index b757eb7c..2f684498 100644 --- a/remote/sys.go +++ b/pkg/remote/sys.go @@ -22,11 +22,11 @@ package remote import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/constants" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/session" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/session" ) // Sys contains logic for handling sys remotes diff --git a/remote/sys_test.go b/pkg/remote/sys_test.go similarity index 97% rename from remote/sys_test.go rename to pkg/remote/sys_test.go index 27b8813f..cf55e2b7 100644 --- a/remote/sys_test.go +++ b/pkg/remote/sys_test.go @@ -22,14 +22,14 @@ package remote import ( "encoding/json" + "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/session/mocks" ) func TestBindSession(t *testing.T) { diff --git a/reporters.go b/pkg/reporters.go similarity index 83% rename from reporters.go rename to pkg/reporters.go index 4572f684..a8c8bf74 100644 --- a/reporters.go +++ b/pkg/reporters.go @@ -1,10 +1,10 @@ -package pitaya +package pkg import ( - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/metrics/models" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/metrics/models" + "github.com/topfreegames/pitaya/v3/pkg/config" ) // CreatePrometheusReporter create a Prometheus reporter instance diff --git a/route/route.go b/pkg/route/route.go similarity index 97% rename from route/route.go rename to pkg/route/route.go index 63555a9b..88b86a30 100644 --- a/route/route.go +++ b/pkg/route/route.go @@ -25,7 +25,7 @@ import ( "fmt" "strings" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) var ( diff --git a/route/route_test.go b/pkg/route/route_test.go similarity index 100% rename from route/route_test.go rename to pkg/route/route_test.go diff --git a/router/router.go b/pkg/router/router.go similarity index 82% rename from router/router.go rename to pkg/router/router.go index 9f9f4087..5f532533 100644 --- a/router/router.go +++ b/pkg/router/router.go @@ -22,20 +22,20 @@ package router import ( "context" + cluster2 "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/constants" "math/rand" "time" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/route" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" ) // Router struct type Router struct { - serviceDiscovery cluster.ServiceDiscovery + serviceDiscovery cluster2.ServiceDiscovery routesMap map[string]RoutingFunc } @@ -44,8 +44,8 @@ type RoutingFunc func( ctx context.Context, route *route.Route, payload []byte, - servers map[string]*cluster.Server, -) (*cluster.Server, error) + servers map[string]*cluster2.Server, +) (*cluster2.Server, error) // New returns the router func New() *Router { @@ -55,14 +55,14 @@ func New() *Router { } // SetServiceDiscovery sets the sd client -func (r *Router) SetServiceDiscovery(sd cluster.ServiceDiscovery) { +func (r *Router) SetServiceDiscovery(sd cluster2.ServiceDiscovery) { r.serviceDiscovery = sd } func (r *Router) defaultRoute( - servers map[string]*cluster.Server, -) *cluster.Server { - srvList := make([]*cluster.Server, 0) + servers map[string]*cluster2.Server, +) *cluster2.Server { + srvList := make([]*cluster2.Server, 0) s := rand.NewSource(time.Now().Unix()) rnd := rand.New(s) for _, v := range servers { @@ -79,7 +79,7 @@ func (r *Router) Route( svType string, route *route.Route, msg *message.Message, -) (*cluster.Server, error) { +) (*cluster2.Server, error) { if r.serviceDiscovery == nil { return nil, constants.ErrServiceDiscoveryNotInitialized } diff --git a/router/router_test.go b/pkg/router/router_test.go similarity index 90% rename from router/router_test.go rename to pkg/router/router_test.go index b8ade8f2..ec29810b 100644 --- a/router/router_test.go +++ b/pkg/router/router_test.go @@ -3,15 +3,15 @@ package router import ( "context" "errors" + "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/cluster/mocks" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/cluster/mocks" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/route" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" ) var ( diff --git a/rpc.go b/pkg/rpc.go similarity index 73% rename from rpc.go rename to pkg/rpc.go index cce98b6b..e38fe9be 100644 --- a/rpc.go +++ b/pkg/rpc.go @@ -18,16 +18,17 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" "reflect" "github.com/golang/protobuf/proto" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/route" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" ) // RPC calls a method in a different server @@ -40,6 +41,39 @@ func (app *App) RPCTo(ctx context.Context, serverID, routeStr string, reply prot return app.doSendRPC(ctx, serverID, routeStr, reply, arg) } +// RawRPC send a rpc to a specific server, in and out will be a byte array, it +// is used by the sidecar +func (app *App) RawRPC(ctx context.Context, serverID, routeStr string, arg []byte) (*protos.Response, error) { + var r *route.Route + var err error + if r, err = app.basicCheckRPC(ctx, serverID, routeStr); err != nil { + return nil, err + } + + return app.remoteService.DoRPC(ctx, serverID, r, arg) +} + +func (app *App) basicCheckRPC(ctx context.Context, serverID, routeStr string) (*route.Route, error) { + if app.rpcServer == nil { + return nil, constants.ErrRPCServerNotInitialized + } + + r, err := route.Decode(routeStr) + if err != nil { + return nil, err + } + + if r.SvType == "" { + return nil, constants.ErrNoServerTypeChosenForRPC + } + + if (r.SvType == app.server.Type && serverID == "") || serverID == app.server.ID { + return nil, constants.ErrNonsenseRPC + } + + return r, nil +} + // ReliableRPC enqueues RPC to worker so it's executed asynchronously // Default enqueue options are used func (app *App) ReliableRPC( @@ -62,26 +96,15 @@ func (app *App) ReliableRPCWithOptions( } func (app *App) doSendRPC(ctx context.Context, serverID, routeStr string, reply proto.Message, arg proto.Message) error { - if app.rpcServer == nil { - return constants.ErrRPCServerNotInitialized + var r *route.Route + var err error + if r, err = app.basicCheckRPC(ctx, serverID, routeStr); err != nil { + return err } if reflect.TypeOf(reply).Kind() != reflect.Ptr { return constants.ErrReplyShouldBePtr } - r, err := route.Decode(routeStr) - if err != nil { - return err - } - - if r.SvType == "" { - return constants.ErrNoServerTypeChosenForRPC - } - - if (r.SvType == app.server.Type && serverID == "") || serverID == app.server.ID { - return constants.ErrNonsenseRPC - } - return app.remoteService.RPC(ctx, serverID, r, reply, arg) } diff --git a/rpc_test.go b/pkg/rpc_test.go similarity index 55% rename from rpc_test.go rename to pkg/rpc_test.go index 7cc98b3e..10912c08 100644 --- a/rpc_test.go +++ b/pkg/rpc_test.go @@ -18,29 +18,29 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/cluster/mocks" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/conn/codec" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "github.com/golang/mock/gomock" "github.com/golang/protobuf/proto" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/cluster" - clustermocks "github.com/topfreegames/pitaya/v2/cluster/mocks" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/conn/codec" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/pipeline" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/protos/test" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/router" - serializemocks "github.com/topfreegames/pitaya/v2/serialize/mocks" - "github.com/topfreegames/pitaya/v2/service" - sessionmocks "github.com/topfreegames/pitaya/v2/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/pipeline" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/protos/test" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/router" + serializemocks "github.com/topfreegames/pitaya/v3/pkg/serialize/mocks" + "github.com/topfreegames/pitaya/v3/pkg/service" + sessionmocks "github.com/topfreegames/pitaya/v3/pkg/session/mocks" ) func TestDoSendRPCNotInitialized(t *testing.T) { @@ -50,6 +50,55 @@ func TestDoSendRPCNotInitialized(t *testing.T) { assert.Equal(t, constants.ErrRPCServerNotInitialized, err) } +func TestRawRPC(t *testing.T) { + config := config.NewDefaultBuilderConfig() + app := NewDefaultApp(true, "testtype", Cluster, map[string]string{}, *config).(*App) + app.server.ID = "myserver" + app.rpcServer = &cluster.NatsRPCServer{} + tables := []struct { + name string + routeStr string + arg []byte + err error + }{ + {"bad_route", "badroute", nil, route.ErrInvalidRoute}, + {"no_server_type", "bla.bla", nil, constants.ErrNoServerTypeChosenForRPC}, + {"nonsense_rpc", "mytype.bla.bla", nil, constants.ErrNonsenseRPC}, + {"success", "bla.bla.bla", []byte{0x01}, nil}, + } + + for _, table := range tables { + t.Run(table.name, func(t *testing.T) { + ctx := context.Background() + + if table.err == nil { + packetEncoder := codec.NewPomeloPacketEncoder() + ctrl := gomock.NewController(t) + defer ctrl.Finish() + mockSerializer := serializemocks.NewMockSerializer(ctrl) + mockSD := mocks.NewMockServiceDiscovery(ctrl) + mockRPCClient := mocks.NewMockRPCClient(ctrl) + mockRPCServer := mocks.NewMockRPCServer(ctrl) + messageEncoder := message.NewMessagesEncoder(false) + sessionPool := sessionmocks.NewMockSessionPool(ctrl) + router := router.New() + handlerPool := service.NewHandlerPool() + svc := service.NewRemoteService(mockRPCClient, mockRPCServer, mockSD, packetEncoder, mockSerializer, router, messageEncoder, &cluster.Server{}, sessionPool, pipeline.NewHandlerHooks(), handlerPool) + assert.NotNil(t, svc) + app.remoteService = svc + app.server.ID = "notmyserver" + b, err := proto.Marshal(&test.SomeStruct{A: 1}) + assert.NoError(t, err) + mockSD.EXPECT().GetServer("myserver").Return(&cluster.Server{}, nil) + mockRPCClient.EXPECT().Call(ctx, protos.RPCType_User, gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(&protos.Response{Data: b}, nil) + } + + _, err := app.RawRPC(ctx, "myserver", table.routeStr, table.arg) + assert.Equal(t, table.err, err) + }) + } +} + func TestDoSendRPC(t *testing.T) { config := config.NewDefaultBuilderConfig() app := NewDefaultApp(true, "testtype", Cluster, map[string]string{}, *config).(*App) @@ -76,9 +125,9 @@ func TestDoSendRPC(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockSD := clustermocks.NewMockServiceDiscovery(ctrl) - mockRPCClient := clustermocks.NewMockRPCClient(ctrl) - mockRPCServer := clustermocks.NewMockRPCServer(ctrl) + mockSD := mocks.NewMockServiceDiscovery(ctrl) + mockRPCClient := mocks.NewMockRPCClient(ctrl) + mockRPCServer := mocks.NewMockRPCServer(ctrl) messageEncoder := message.NewMessagesEncoder(false) sessionPool := sessionmocks.NewMockSessionPool(ctrl) router := router.New() diff --git a/serialize/json/json.go b/pkg/serialize/json/json.go similarity index 100% rename from serialize/json/json.go rename to pkg/serialize/json/json.go diff --git a/serialize/json/json_test.go b/pkg/serialize/json/json_test.go similarity index 100% rename from serialize/json/json_test.go rename to pkg/serialize/json/json_test.go diff --git a/serialize/mocks/serializer.go b/pkg/serialize/mocks/serializer.go similarity index 80% rename from serialize/mocks/serializer.go rename to pkg/serialize/mocks/serializer.go index 9ebd4b4f..be608e95 100644 --- a/serialize/mocks/serializer.go +++ b/pkg/serialize/mocks/serializer.go @@ -1,38 +1,39 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/topfreegames/pitaya/v2/serialize (interfaces: Serializer) +// Source: github.com/topfreegames/pitaya/v3/pkg/serialize (interfaces: Serializer) // Package mocks is a generated GoMock package. package mocks import ( - gomock "github.com/golang/mock/gomock" reflect "reflect" + + gomock "github.com/golang/mock/gomock" ) -// MockSerializer is a mock of Serializer interface +// MockSerializer is a mock of Serializer interface. type MockSerializer struct { ctrl *gomock.Controller recorder *MockSerializerMockRecorder } -// MockSerializerMockRecorder is the mock recorder for MockSerializer +// MockSerializerMockRecorder is the mock recorder for MockSerializer. type MockSerializerMockRecorder struct { mock *MockSerializer } -// NewMockSerializer creates a new mock instance +// NewMockSerializer creates a new mock instance. func NewMockSerializer(ctrl *gomock.Controller) *MockSerializer { mock := &MockSerializer{ctrl: ctrl} mock.recorder = &MockSerializerMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use +// EXPECT returns an object that allows the caller to indicate expected use. func (m *MockSerializer) EXPECT() *MockSerializerMockRecorder { return m.recorder } -// GetName mocks base method +// GetName mocks base method. func (m *MockSerializer) GetName() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetName") @@ -40,13 +41,13 @@ func (m *MockSerializer) GetName() string { return ret0 } -// GetName indicates an expected call of GetName +// GetName indicates an expected call of GetName. func (mr *MockSerializerMockRecorder) GetName() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetName", reflect.TypeOf((*MockSerializer)(nil).GetName)) } -// Marshal mocks base method +// Marshal mocks base method. func (m *MockSerializer) Marshal(arg0 interface{}) ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Marshal", arg0) @@ -55,13 +56,13 @@ func (m *MockSerializer) Marshal(arg0 interface{}) ([]byte, error) { return ret0, ret1 } -// Marshal indicates an expected call of Marshal +// Marshal indicates an expected call of Marshal. func (mr *MockSerializerMockRecorder) Marshal(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Marshal", reflect.TypeOf((*MockSerializer)(nil).Marshal), arg0) } -// Unmarshal mocks base method +// Unmarshal mocks base method. func (m *MockSerializer) Unmarshal(arg0 []byte, arg1 interface{}) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Unmarshal", arg0, arg1) @@ -69,7 +70,7 @@ func (m *MockSerializer) Unmarshal(arg0 []byte, arg1 interface{}) error { return ret0 } -// Unmarshal indicates an expected call of Unmarshal +// Unmarshal indicates an expected call of Unmarshal. func (mr *MockSerializerMockRecorder) Unmarshal(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unmarshal", reflect.TypeOf((*MockSerializer)(nil).Unmarshal), arg0, arg1) diff --git a/serialize/protobuf/fixtures/TestMarshal/test_ok.golden b/pkg/serialize/protobuf/fixtures/TestMarshal/test_ok.golden similarity index 100% rename from serialize/protobuf/fixtures/TestMarshal/test_ok.golden rename to pkg/serialize/protobuf/fixtures/TestMarshal/test_ok.golden diff --git a/serialize/protobuf/protobuf.go b/pkg/serialize/protobuf/protobuf.go similarity index 97% rename from serialize/protobuf/protobuf.go rename to pkg/serialize/protobuf/protobuf.go index 3a350da5..6d6e90f1 100644 --- a/serialize/protobuf/protobuf.go +++ b/pkg/serialize/protobuf/protobuf.go @@ -22,7 +22,7 @@ package protobuf import ( "github.com/golang/protobuf/proto" - "github.com/topfreegames/pitaya/v2/constants" + "github.com/topfreegames/pitaya/v3/pkg/constants" ) // Serializer implements the serialize.Serializer interface diff --git a/serialize/protobuf/protobuf_test.go b/pkg/serialize/protobuf/protobuf_test.go similarity index 91% rename from serialize/protobuf/protobuf_test.go rename to pkg/serialize/protobuf/protobuf_test.go index 5aab8653..afaf6fb4 100644 --- a/serialize/protobuf/protobuf_test.go +++ b/pkg/serialize/protobuf/protobuf_test.go @@ -22,13 +22,14 @@ package protobuf import ( "flag" + "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "github.com/stretchr/testify/assert" + "google.golang.org/protobuf/proto" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/helpers" - "github.com/topfreegames/pitaya/v2/protos" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/protos" ) var update = flag.Bool("update", false, "update .golden files") @@ -92,7 +93,7 @@ func TestUnmarshal(t *testing.T) { err := serializer.Unmarshal(table.data, result) assert.Equal(t, table.err, err) if table.err == nil { - assert.Equal(t, table.expected, result) + assert.True(t, proto.Equal(table.expected.(*protos.Response), result.(*protos.Response))) } }) } diff --git a/serialize/serializer.go b/pkg/serialize/serializer.go similarity index 100% rename from serialize/serializer.go rename to pkg/serialize/serializer.go diff --git a/service/base_service.go b/pkg/service/base_service.go similarity index 77% rename from service/base_service.go rename to pkg/service/base_service.go index 83481068..09b37f06 100644 --- a/service/base_service.go +++ b/pkg/service/base_service.go @@ -1,6 +1,6 @@ package service -import "github.com/topfreegames/pitaya/v2/pipeline" +import "github.com/topfreegames/pitaya/v3/pkg/pipeline" type baseService struct { handlerHooks *pipeline.HandlerHooks diff --git a/service/fixtures/unmarshal_remote_test_1.golden b/pkg/service/fixtures/unmarshal_remote_test_1.golden similarity index 100% rename from service/fixtures/unmarshal_remote_test_1.golden rename to pkg/service/fixtures/unmarshal_remote_test_1.golden diff --git a/service/fixtures/unmarshal_remote_test_2.golden b/pkg/service/fixtures/unmarshal_remote_test_2.golden similarity index 100% rename from service/fixtures/unmarshal_remote_test_2.golden rename to pkg/service/fixtures/unmarshal_remote_test_2.golden diff --git a/service/fixtures/unmarshal_remote_test_3.golden b/pkg/service/fixtures/unmarshal_remote_test_3.golden similarity index 100% rename from service/fixtures/unmarshal_remote_test_3.golden rename to pkg/service/fixtures/unmarshal_remote_test_3.golden diff --git a/service/handler.go b/pkg/service/handler.go similarity index 77% rename from service/handler.go rename to pkg/service/handler.go index 7b84beaa..cb1a9789 100644 --- a/service/handler.go +++ b/pkg/service/handler.go @@ -25,30 +25,30 @@ import ( "encoding/json" "fmt" "github.com/nats-io/nuid" + "github.com/topfreegames/pitaya/v3/pkg/acceptor" + "github.com/topfreegames/pitaya/v3/pkg/agent" + "github.com/topfreegames/pitaya/v3/pkg/cluster" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/conn/codec" + message2 "github.com/topfreegames/pitaya/v3/pkg/conn/message" + packet2 "github.com/topfreegames/pitaya/v3/pkg/conn/packet" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" + "github.com/topfreegames/pitaya/v3/pkg/docgenerator" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "strings" "time" - "github.com/topfreegames/pitaya/v2/acceptor" - "github.com/topfreegames/pitaya/v2/pipeline" + "github.com/topfreegames/pitaya/v3/pkg/pipeline" opentracing "github.com/opentracing/opentracing-go" - "github.com/topfreegames/pitaya/v2/agent" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/conn/codec" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/conn/packet" - "github.com/topfreegames/pitaya/v2/constants" - pcontext "github.com/topfreegames/pitaya/v2/context" - "github.com/topfreegames/pitaya/v2/docgenerator" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/serialize" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/timer" - "github.com/topfreegames/pitaya/v2/tracing" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/serialize" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/timer" + "github.com/topfreegames/pitaya/v3/pkg/tracing" ) var ( @@ -63,20 +63,20 @@ type ( chRemoteProcess chan unhandledMessage // channel of messages that will be processed remotely decoder codec.PacketDecoder // binary decoder remoteService *RemoteService - serializer serialize.Serializer // message serializer - server *cluster.Server // server obj - services map[string]*component.Service // all registered service + serializer serialize.Serializer // message serializer + server *cluster.Server // server obj + services map[string]*component2.Service // all registered service metricsReporters []metrics.Reporter agentFactory agent.AgentFactory handlerPool *HandlerPool - handlers map[string]*component.Handler // all handler method + handlers map[string]*component2.Handler // all handler method } unhandledMessage struct { ctx context.Context agent agent.Agent route *route.Route - msg *message.Message + msg *message2.Message } ) @@ -94,7 +94,7 @@ func NewHandlerService( handlerPool *HandlerPool, ) *HandlerService { h := &HandlerService{ - services: make(map[string]*component.Service), + services: make(map[string]*component2.Service), chLocalProcess: make(chan unhandledMessage, localProcessBufferSize), chRemoteProcess: make(chan unhandledMessage, remoteProcessBufferSize), decoder: packetDecoder, @@ -104,7 +104,7 @@ func NewHandlerService( agentFactory: agentFactory, metricsReporters: metricsReporters, handlerPool: handlerPool, - handlers: make(map[string]*component.Handler), + handlers: make(map[string]*component2.Handler), } h.handlerHooks = handlerHooks @@ -141,8 +141,8 @@ func (h *HandlerService) Dispatch(thread int) { } // Register registers components -func (h *HandlerService) Register(comp component.Component, opts []component.Option) error { - s := component.NewService(comp, opts) +func (h *HandlerService) Register(comp component2.Component, opts []component2.Option) error { + s := component2.NewService(comp, opts) if _, ok := h.services[s.Name]; ok { return fmt.Errorf("handler: service already defined: %s", s.Name) @@ -180,7 +180,7 @@ func (h *HandlerService) Handle(conn acceptor.PlayerConn) { msg, err := conn.GetNextMessage() if err != nil { - if err != constants.ErrConnectionClosed { + if err != constants2.ErrConnectionClosed { logger.Log.Errorf("Error reading next available message: %s", err.Error()) } @@ -208,9 +208,9 @@ func (h *HandlerService) Handle(conn acceptor.PlayerConn) { } } -func (h *HandlerService) processPacket(a agent.Agent, p *packet.Packet) error { +func (h *HandlerService) processPacket(a agent.Agent, p *packet2.Packet) error { switch p.Type { - case packet.Handshake: + case packet2.Handshake: logger.Log.Debug("Received handshake packet") if err := a.SendHandshakeResponse(); err != nil { logger.Log.Errorf("Error sending handshake response: %s", err.Error()) @@ -222,36 +222,36 @@ func (h *HandlerService) processPacket(a agent.Agent, p *packet.Packet) error { handshakeData := &session.HandshakeData{} err := json.Unmarshal(p.Data, handshakeData) if err != nil { - a.SetStatus(constants.StatusClosed) + a.SetStatus(constants2.StatusClosed) return fmt.Errorf("Invalid handshake data. Id=%d", a.GetSession().ID()) } a.GetSession().SetHandshakeData(handshakeData) - a.SetStatus(constants.StatusHandshake) - err = a.GetSession().Set(constants.IPVersionKey, a.IPVersion()) + a.SetStatus(constants2.StatusHandshake) + err = a.GetSession().Set(constants2.IPVersionKey, a.IPVersion()) if err != nil { logger.Log.Warnf("failed to save ip version on session: %q\n", err) } logger.Log.Debug("Successfully saved handshake data") - case packet.HandshakeAck: - a.SetStatus(constants.StatusWorking) + case packet2.HandshakeAck: + a.SetStatus(constants2.StatusWorking) logger.Log.Debugf("Receive handshake ACK Id=%d, Remote=%s", a.GetSession().ID(), a.RemoteAddr()) - case packet.Data: - if a.GetStatus() < constants.StatusWorking { + case packet2.Data: + if a.GetStatus() < constants2.StatusWorking { return fmt.Errorf("receive data on socket which is not yet ACK, session will be closed immediately, remote=%s", a.RemoteAddr().String()) } - msg, err := message.Decode(p.Data) + msg, err := message2.Decode(p.Data) if err != nil { return err } h.processMessage(a, msg) - case packet.Heartbeat: + case packet2.Heartbeat: // expected } @@ -259,11 +259,11 @@ func (h *HandlerService) processPacket(a agent.Agent, p *packet.Packet) error { return nil } -func (h *HandlerService) processMessage(a agent.Agent, msg *message.Message) { +func (h *HandlerService) processMessage(a agent.Agent, msg *message2.Message) { requestID := nuid.New() - ctx := pcontext.AddToPropagateCtx(context.Background(), constants.StartTimeKey, time.Now().UnixNano()) - ctx = pcontext.AddToPropagateCtx(ctx, constants.RouteKey, msg.Route) - ctx = pcontext.AddToPropagateCtx(ctx, constants.RequestIDKey, requestID) + ctx := pcontext.AddToPropagateCtx(context.Background(), constants2.StartTimeKey, time.Now().UnixNano()) + ctx = pcontext.AddToPropagateCtx(ctx, constants2.RouteKey, msg.Route) + ctx = pcontext.AddToPropagateCtx(ctx, constants2.RequestIDKey, requestID) tags := opentracing.Tags{ "local.id": h.server.ID, "span.kind": "server", @@ -272,7 +272,7 @@ func (h *HandlerService) processMessage(a agent.Agent, msg *message.Message) { "request.id": requestID, } ctx = tracing.StartSpan(ctx, msg.Route, tags) - ctx = context.WithValue(ctx, constants.SessionCtxKey, a.GetSession()) + ctx = context.WithValue(ctx, constants2.SessionCtxKey, a.GetSession()) r, err := route.Decode(msg.Route) if err != nil { @@ -302,17 +302,17 @@ func (h *HandlerService) processMessage(a agent.Agent, msg *message.Message) { } } -func (h *HandlerService) localProcess(ctx context.Context, a agent.Agent, route *route.Route, msg *message.Message) { +func (h *HandlerService) localProcess(ctx context.Context, a agent.Agent, route *route.Route, msg *message2.Message) { var mid uint switch msg.Type { - case message.Request: + case message2.Request: mid = msg.ID - case message.Notify: + case message2.Notify: mid = 0 } ret, err := h.handlerPool.ProcessHandlerMessage(ctx, route, h.serializer, h.handlerHooks, a.GetSession(), msg.Data, msg.Type, false) - if msg.Type != message.Notify { + if msg.Type != message2.Notify { if err != nil { logger.Log.Errorf("Failed to process handler message: %s", err.Error()) a.AnswerWithError(ctx, mid, err) diff --git a/service/handler_pool.go b/pkg/service/handler_pool.go similarity index 85% rename from service/handler_pool.go rename to pkg/service/handler_pool.go index 58245d84..e81421ad 100644 --- a/service/handler_pool.go +++ b/pkg/service/handler_pool.go @@ -3,18 +3,18 @@ package service import ( "context" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/constants" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "reflect" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/logger/interfaces" - "github.com/topfreegames/pitaya/v2/pipeline" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/serialize" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/util" + "github.com/topfreegames/pitaya/v3/pkg/logger/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/pipeline" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/serialize" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/util" ) // HandlerPool ... diff --git a/service/handler_pool_test.go b/pkg/service/handler_pool_test.go similarity index 94% rename from service/handler_pool_test.go rename to pkg/service/handler_pool_test.go index 67747321..d1b66d71 100644 --- a/service/handler_pool_test.go +++ b/pkg/service/handler_pool_test.go @@ -24,21 +24,21 @@ import ( "context" "errors" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/constants" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "reflect" "testing" "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/pipeline" - "github.com/topfreegames/pitaya/v2/protos/test" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/serialize/mocks" - session_mocks "github.com/topfreegames/pitaya/v2/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/pipeline" + "github.com/topfreegames/pitaya/v3/pkg/protos/test" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/serialize/mocks" + session_mocks "github.com/topfreegames/pitaya/v3/pkg/session/mocks" ) func TestGetHandlerExists(t *testing.T) { diff --git a/service/handler_test.go b/pkg/service/handler_test.go similarity index 79% rename from service/handler_test.go rename to pkg/service/handler_test.go index ee050545..fe0c63a2 100644 --- a/service/handler_test.go +++ b/pkg/service/handler_test.go @@ -24,6 +24,14 @@ import ( "context" encjson "encoding/json" "errors" + agentmocks "github.com/topfreegames/pitaya/v3/pkg/agent/mocks" + "github.com/topfreegames/pitaya/v3/pkg/cluster" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" + codec2 "github.com/topfreegames/pitaya/v3/pkg/conn/codec" + message2 "github.com/topfreegames/pitaya/v3/pkg/conn/message" + packet2 "github.com/topfreegames/pitaya/v3/pkg/conn/packet" + "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" "reflect" "sync" "testing" @@ -31,25 +39,17 @@ import ( "github.com/golang/mock/gomock" "github.com/google/uuid" "github.com/stretchr/testify/assert" - agentmocks "github.com/topfreegames/pitaya/v2/agent/mocks" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/conn/codec" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/conn/packet" - "github.com/topfreegames/pitaya/v2/constants" - pcontext "github.com/topfreegames/pitaya/v2/context" - "github.com/topfreegames/pitaya/v2/helpers" - "github.com/topfreegames/pitaya/v2/metrics" - metricsmocks "github.com/topfreegames/pitaya/v2/metrics/mocks" - connmock "github.com/topfreegames/pitaya/v2/mocks" - "github.com/topfreegames/pitaya/v2/pipeline" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/serialize/json" - serializemocks "github.com/topfreegames/pitaya/v2/serialize/mocks" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + metricsmocks "github.com/topfreegames/pitaya/v3/pkg/metrics/mocks" + connmock "github.com/topfreegames/pitaya/v3/pkg/mocks" + "github.com/topfreegames/pitaya/v3/pkg/pipeline" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/serialize/json" + serializemocks "github.com/topfreegames/pitaya/v3/pkg/serialize/mocks" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/session/mocks" ) var ( @@ -62,7 +62,7 @@ func (m *mockAddr) Network() string { return "" } func (m *mockAddr) String() string { return "remote-string" } type MyComp struct { - component.Base + component2.Base } func (m *MyComp) Init() {} @@ -76,14 +76,14 @@ func (m *MyComp) HandlerRawRaw(ctx context.Context, b []byte) ([]byte, error) { } type NoHandlerRemoteComp struct { - component.Base + component2.Base } func (m *NoHandlerRemoteComp) Init() {} func (m *NoHandlerRemoteComp) Shutdown() {} func TestNewHandlerService(t *testing.T) { - packetDecoder := codec.NewPomeloPacketDecoder() + packetDecoder := codec2.NewPomeloPacketDecoder() serializer := json.NewSerializer() sv := &cluster.Server{} remoteSvc := &RemoteService{} @@ -122,7 +122,7 @@ func TestNewHandlerService(t *testing.T) { func TestHandlerServiceRegister(t *testing.T) { handlerPool := NewHandlerPool() svc := NewHandlerService(nil, nil, 0, 0, nil, nil, nil, nil, nil, handlerPool) - err := svc.Register(&MyComp{}, []component.Option{}) + err := svc.Register(&MyComp{}, []component2.Option{}) assert.NoError(t, err) assert.Len(t, svc.services, 1) val, ok := svc.services["MyComp"] @@ -142,29 +142,29 @@ func TestHandlerServiceRegister(t *testing.T) { func TestHandlerServiceRegisterFailsIfRegisterTwice(t *testing.T) { handlerPool := NewHandlerPool() svc := NewHandlerService(nil, nil, 0, 0, nil, nil, nil, nil, nil, handlerPool) - err := svc.Register(&MyComp{}, []component.Option{}) + err := svc.Register(&MyComp{}, []component2.Option{}) assert.NoError(t, err) - err = svc.Register(&MyComp{}, []component.Option{}) + err = svc.Register(&MyComp{}, []component2.Option{}) assert.Contains(t, err.Error(), "handler: service already defined") } func TestHandlerServiceRegisterFailsIfNoHandlerMethods(t *testing.T) { handlerPool := NewHandlerPool() svc := NewHandlerService(nil, nil, 0, 0, nil, nil, nil, nil, nil, handlerPool) - err := svc.Register(&NoHandlerRemoteComp{}, []component.Option{}) + err := svc.Register(&NoHandlerRemoteComp{}, []component2.Option{}) assert.Equal(t, errors.New("type NoHandlerRemoteComp has no exported methods of handler type"), err) } func TestHandlerServiceProcessMessage(t *testing.T) { tables := []struct { name string - msg *message.Message + msg *message2.Message err interface{} local bool }{ - {"failed_decode", &message.Message{ID: 1, Route: "k.k.k.k"}, &protos.Error{Msg: "invalid route", Code: "PIT-400"}, false}, - {"local_process", &message.Message{ID: 1, Route: "k.k"}, nil, true}, - {"remote_process", &message.Message{ID: 1, Route: "k.k.k"}, nil, false}, + {"failed_decode", &message2.Message{ID: 1, Route: "k.k.k.k"}, &protos.Error{Msg: "invalid route", Code: "PIT-400"}, false}, + {"local_process", &message2.Message{ID: 1, Route: "k.k"}, nil, true}, + {"remote_process", &message2.Message{ID: 1, Route: "k.k.k"}, nil, false}, } for _, table := range tables { @@ -209,16 +209,16 @@ func TestHandlerServiceLocalProcess(t *testing.T) { assert.NotNil(t, m) rt := route.NewRoute("", uuid.New().String(), uuid.New().String()) handlerPool := NewHandlerPool() - handlerPool.handlers[rt.Short()] = &component.Handler{Receiver: reflect.ValueOf(tObj), Method: m, Type: m.Type.In(2), IsRawArg: true} + handlerPool.handlers[rt.Short()] = &component2.Handler{Receiver: reflect.ValueOf(tObj), Method: m, Type: m.Type.In(2), IsRawArg: true} tables := []struct { name string - msg *message.Message + msg *message2.Message rt *route.Route err interface{} }{ - {"process_handler_msg_err", &message.Message{}, route.NewRoute("bla", "bla", "bla"), &protos.Error{Msg: "pitaya/handler: bla.bla.bla not found", Code: "PIT-404"}}, - {"success", &message.Message{ID: 1, Data: []byte(`["ok"]`)}, rt, nil}, + {"process_handler_msg_err", &message2.Message{}, route.NewRoute("bla", "bla", "bla"), &protos.Error{Msg: "pitaya/handler: bla.bla.bla not found", Code: "PIT-404"}}, + {"success", &message2.Message{ID: 1, Data: []byte(`["ok"]`)}, rt, nil}, } for _, table := range tables { t.Run(table.name, func(t *testing.T) { @@ -250,12 +250,12 @@ func TestHandlerServiceLocalProcess(t *testing.T) { func TestHandlerServiceProcessPacketHandshake(t *testing.T) { tables := []struct { name string - packet *packet.Packet + packet *packet2.Packet socketStatus int32 errStr string }{ - {"invalid_handshake_data", &packet.Packet{Type: packet.Handshake, Data: []byte("asiodjasd")}, constants.StatusClosed, "Invalid handshake data"}, - {"valid_handshake_data", &packet.Packet{Type: packet.Handshake, Data: []byte(`{"sys":{"platform":"mac"}}`)}, constants.StatusHandshake, ""}, + {"invalid_handshake_data", &packet2.Packet{Type: packet2.Handshake, Data: []byte("asiodjasd")}, constants.StatusClosed, "Invalid handshake data"}, + {"valid_handshake_data", &packet2.Packet{Type: packet2.Handshake, Data: []byte(`{"sys":{"platform":"mac"}}`)}, constants.StatusHandshake, ""}, } for _, table := range tables { t.Run(table.name, func(t *testing.T) { @@ -313,7 +313,7 @@ func TestHandlerServiceProcessPacketHandshakeAck(t *testing.T) { mockAgent.EXPECT().RemoteAddr().Return(&mockAddr{}) mockAgent.EXPECT().SetLastAt() - err := svc.processPacket(mockAgent, &packet.Packet{Type: packet.HandshakeAck}) + err := svc.processPacket(mockAgent, &packet2.Packet{Type: packet2.HandshakeAck}) assert.NoError(t, err) } @@ -327,25 +327,25 @@ func TestHandlerServiceProcessPacketHeartbeat(t *testing.T) { handlerPool := NewHandlerPool() svc := NewHandlerService(nil, nil, 1, 1, nil, nil, nil, nil, nil, handlerPool) - err := svc.processPacket(mockAgent, &packet.Packet{Type: packet.Heartbeat}) + err := svc.processPacket(mockAgent, &packet2.Packet{Type: packet2.Heartbeat}) assert.NoError(t, err) } func TestHandlerServiceProcessPacketData(t *testing.T) { msgID := uint(1) - msg := &message.Message{Type: message.Request, ID: msgID, Data: []byte("ok")} - messageEncoder := message.NewMessagesEncoder(false) + msg := &message2.Message{Type: message2.Request, ID: msgID, Data: []byte("ok")} + messageEncoder := message2.NewMessagesEncoder(false) encodedMsg, err := messageEncoder.Encode(msg) assert.NoError(t, err) tables := []struct { name string - packet *packet.Packet + packet *packet2.Packet socketStatus int32 errStr string }{ - {"not_acked_socket", &packet.Packet{Type: packet.Data, Data: []byte("ok")}, constants.StatusStart, "not yet ACK"}, - {"failed_decode", &packet.Packet{Type: packet.Data, Data: []byte("ok")}, constants.StatusWorking, "wrong message type"}, - {"success", &packet.Packet{Type: packet.Data, Data: encodedMsg}, constants.StatusWorking, ""}, + {"not_acked_socket", &packet2.Packet{Type: packet2.Data, Data: []byte("ok")}, constants.StatusStart, "not yet ACK"}, + {"failed_decode", &packet2.Packet{Type: packet2.Data, Data: []byte("ok")}, constants.StatusWorking, "wrong message type"}, + {"success", &packet2.Packet{Type: packet2.Data, Data: encodedMsg}, constants.StatusWorking, ""}, } for _, table := range tables { t.Run(table.name, func(t *testing.T) { @@ -383,10 +383,10 @@ func TestHandlerServiceHandle(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - packetEncoder := codec.NewPomeloPacketEncoder() - packetDecoder := codec.NewPomeloPacketDecoder() + packetEncoder := codec2.NewPomeloPacketEncoder() + packetDecoder := codec2.NewPomeloPacketDecoder() handshakeBuffer := `{"sys":{"platform":"mac","libVersion":"0.3.5-release","clientBuildNumber":"20","clientVersion":"2.1"},"user":{"age":30}}` - bbb, err := packetEncoder.Encode(packet.Handshake, []byte(handshakeBuffer)) + bbb, err := packetEncoder.Encode(packet2.Handshake, []byte(handshakeBuffer)) assert.NoError(t, err) mockSerializer := serializemocks.NewMockSerializer(ctrl) diff --git a/service/remote.go b/pkg/service/remote.go similarity index 84% rename from service/remote.go rename to pkg/service/remote.go index fa891532..3dce88f8 100644 --- a/service/remote.go +++ b/pkg/service/remote.go @@ -24,63 +24,63 @@ import ( "context" "errors" "fmt" + agent2 "github.com/topfreegames/pitaya/v3/pkg/agent" + cluster2 "github.com/topfreegames/pitaya/v3/pkg/cluster" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/conn/codec" + message2 "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/constants" + "github.com/topfreegames/pitaya/v3/pkg/docgenerator" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "reflect" "github.com/golang/protobuf/proto" - "github.com/topfreegames/pitaya/v2/agent" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/conn/codec" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/docgenerator" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/pipeline" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/router" - "github.com/topfreegames/pitaya/v2/serialize" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/tracing" - "github.com/topfreegames/pitaya/v2/util" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/pipeline" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/router" + "github.com/topfreegames/pitaya/v3/pkg/serialize" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/tracing" + "github.com/topfreegames/pitaya/v3/pkg/util" ) // RemoteService struct type RemoteService struct { baseService - rpcServer cluster.RPCServer - serviceDiscovery cluster.ServiceDiscovery + rpcServer cluster2.RPCServer + serviceDiscovery cluster2.ServiceDiscovery serializer serialize.Serializer encoder codec.PacketEncoder - rpcClient cluster.RPCClient - services map[string]*component.Service // all registered service + rpcClient cluster2.RPCClient + services map[string]*component2.Service // all registered service router *router.Router - messageEncoder message.Encoder - server *cluster.Server // server obj - remoteBindingListeners []cluster.RemoteBindingListener + messageEncoder message2.Encoder + server *cluster2.Server // server obj + remoteBindingListeners []cluster2.RemoteBindingListener sessionPool session.SessionPool handlerPool *HandlerPool - remotes map[string]*component.Remote // all remote method + remotes map[string]*component2.Remote // all remote method } // NewRemoteService creates and return a new RemoteService func NewRemoteService( - rpcClient cluster.RPCClient, - rpcServer cluster.RPCServer, - sd cluster.ServiceDiscovery, + rpcClient cluster2.RPCClient, + rpcServer cluster2.RPCServer, + sd cluster2.ServiceDiscovery, encoder codec.PacketEncoder, serializer serialize.Serializer, router *router.Router, - messageEncoder message.Encoder, - server *cluster.Server, + messageEncoder message2.Encoder, + server *cluster2.Server, sessionPool session.SessionPool, handlerHooks *pipeline.HandlerHooks, handlerPool *HandlerPool, ) *RemoteService { remote := &RemoteService{ - services: make(map[string]*component.Service), + services: make(map[string]*component2.Service), rpcClient: rpcClient, rpcServer: rpcServer, encoder: encoder, @@ -89,10 +89,10 @@ func NewRemoteService( router: router, messageEncoder: messageEncoder, server: server, - remoteBindingListeners: make([]cluster.RemoteBindingListener, 0), + remoteBindingListeners: make([]cluster2.RemoteBindingListener, 0), sessionPool: sessionPool, handlerPool: handlerPool, - remotes: make(map[string]*component.Remote), + remotes: make(map[string]*component2.Remote), } remote.handlerHooks = handlerHooks @@ -102,14 +102,14 @@ func NewRemoteService( func (r *RemoteService) remoteProcess( ctx context.Context, - server *cluster.Server, - a agent.Agent, + server *cluster2.Server, + a agent2.Agent, route *route.Route, - msg *message.Message, + msg *message2.Message, ) { res, err := r.remoteCall(ctx, server, protos.RPCType_Sys, route, a.GetSession(), msg) switch msg.Type { - case message.Request: + case message2.Request: if err != nil { logger.Log.Errorf("Failed to process remote server: %s", err.Error()) a.AnswerWithError(ctx, msg.ID, err) @@ -120,7 +120,7 @@ func (r *RemoteService) remoteProcess( logger.Log.Errorf("Failed to respond to remote server: %s", err.Error()) a.AnswerWithError(ctx, msg.ID, err) } - case message.Notify: + case message2.Notify: defer tracing.FinishSpan(ctx, err) if err == nil && res.Error != nil { err = errors.New(res.Error.GetMsg()) @@ -132,7 +132,7 @@ func (r *RemoteService) remoteProcess( } // AddRemoteBindingListener adds a listener -func (r *RemoteService) AddRemoteBindingListener(bindingListener cluster.RemoteBindingListener) { +func (r *RemoteService) AddRemoteBindingListener(bindingListener cluster2.RemoteBindingListener) { r.remoteBindingListeners = append(r.remoteBindingListeners, bindingListener) } @@ -204,8 +204,8 @@ func (r *RemoteService) KickUser(ctx context.Context, kick *protos.KickMsg) (*pr // DoRPC do rpc and get answer func (r *RemoteService) DoRPC(ctx context.Context, serverID string, route *route.Route, protoData []byte) (*protos.Response, error) { - msg := &message.Message{ - Type: message.Request, + msg := &message2.Message{ + Type: message2.Request, Route: route.Short(), Data: protoData, } @@ -255,8 +255,8 @@ func (r *RemoteService) RPC(ctx context.Context, serverID string, route *route.R } // Register registers components -func (r *RemoteService) Register(comp component.Component, opts []component.Option) error { - s := component.NewService(comp, opts) +func (r *RemoteService) Register(comp component2.Component, opts []component2.Option) error { + s := component2.NewService(comp, opts) if _, ok := r.services[s.Name]; ok { return fmt.Errorf("remote: service already defined: %s", s.Name) @@ -388,7 +388,7 @@ func (r *RemoteService) handleRPCSys(ctx context.Context, req *protos.Request, r reply := req.GetMsg().GetReply() response := &protos.Response{} // (warning) a new agent is created for every new request - a, err := agent.NewRemote( + a, err := agent2.NewRemote( req.GetSession(), reply, r.rpcClient, @@ -433,11 +433,11 @@ func (r *RemoteService) handleRPCSys(ctx context.Context, req *protos.Request, r func (r *RemoteService) remoteCall( ctx context.Context, - server *cluster.Server, + server *cluster2.Server, rpcType protos.RPCType, route *route.Route, session session.Session, - msg *message.Message, + msg *message2.Message, ) (*protos.Response, error) { svType := route.SvType diff --git a/service/remote_test.go b/pkg/service/remote_test.go similarity index 82% rename from service/remote_test.go rename to pkg/service/remote_test.go index 779854cf..4e7fc2ae 100644 --- a/service/remote_test.go +++ b/pkg/service/remote_test.go @@ -23,6 +23,15 @@ package service import ( "context" "errors" + agentmocks "github.com/topfreegames/pitaya/v3/pkg/agent/mocks" + "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/cluster/mocks" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/conn/codec" + message2 "github.com/topfreegames/pitaya/v3/pkg/conn/message" + messagemocks "github.com/topfreegames/pitaya/v3/pkg/conn/message/mocks" + "github.com/topfreegames/pitaya/v3/pkg/constants" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "math/rand" "reflect" "testing" @@ -31,23 +40,14 @@ import ( "github.com/golang/protobuf/proto" "github.com/google/uuid" "github.com/stretchr/testify/assert" - agentmocks "github.com/topfreegames/pitaya/v2/agent/mocks" - "github.com/topfreegames/pitaya/v2/cluster" - clustermocks "github.com/topfreegames/pitaya/v2/cluster/mocks" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/conn/codec" - "github.com/topfreegames/pitaya/v2/conn/message" - messagemocks "github.com/topfreegames/pitaya/v2/conn/message/mocks" - "github.com/topfreegames/pitaya/v2/constants" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/pipeline" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/protos/test" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/router" - serializemocks "github.com/topfreegames/pitaya/v2/serialize/mocks" - "github.com/topfreegames/pitaya/v2/session" - sessionmocks "github.com/topfreegames/pitaya/v2/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/pipeline" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/protos/test" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/router" + serializemocks "github.com/topfreegames/pitaya/v3/pkg/serialize/mocks" + "github.com/topfreegames/pitaya/v3/pkg/session" + sessionmocks "github.com/topfreegames/pitaya/v3/pkg/session/mocks" ) func (m *MyComp) Remote1(ctx context.Context, ss *test.SomeStruct) (*test.SomeStruct, error) { @@ -73,9 +73,9 @@ func TestNewRemoteService(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockSD := clustermocks.NewMockServiceDiscovery(ctrl) - mockRPCClient := clustermocks.NewMockRPCClient(ctrl) - mockRPCServer := clustermocks.NewMockRPCServer(ctrl) + mockSD := mocks.NewMockServiceDiscovery(ctrl) + mockRPCClient := mocks.NewMockRPCClient(ctrl) + mockRPCServer := mocks.NewMockRPCServer(ctrl) mockMessageEncoder := messagemocks.NewMockEncoder(ctrl) router := router.New() sv := &cluster.Server{} @@ -100,9 +100,9 @@ func TestNewRemoteService(t *testing.T) { func TestRemoteServiceRegister(t *testing.T) { svc := NewRemoteService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) - err := svc.Register(&MyComp{}, []component.Option{}) + err := svc.Register(&MyComp{}, []component2.Option{}) assert.NoError(t, err) - defer func() { svc.remotes = make(map[string]*component.Remote, 0) }() + defer func() { svc.remotes = make(map[string]*component2.Remote, 0) }() assert.Len(t, svc.services, 1) val, ok := svc.services["MyComp"] assert.True(t, ok) @@ -125,7 +125,7 @@ func TestRemoteServiceAddRemoteBindingListener(t *testing.T) { svc := NewRemoteService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) ctrl := gomock.NewController(t) defer ctrl.Finish() - mockBindingListener := clustermocks.NewMockRemoteBindingListener(ctrl) + mockBindingListener := mocks.NewMockRemoteBindingListener(ctrl) svc.AddRemoteBindingListener(mockBindingListener) assert.Equal(t, mockBindingListener, svc.remoteBindingListeners[0]) @@ -135,7 +135,7 @@ func TestRemoteServiceSessionBindRemote(t *testing.T) { svc := NewRemoteService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) ctrl := gomock.NewController(t) defer ctrl.Finish() - mockBindingListener := clustermocks.NewMockRemoteBindingListener(ctrl) + mockBindingListener := mocks.NewMockRemoteBindingListener(ctrl) svc.AddRemoteBindingListener(mockBindingListener) assert.Equal(t, mockBindingListener, svc.remoteBindingListeners[0]) @@ -245,15 +245,15 @@ func TestRemoteServiceKickUser(t *testing.T) { func TestRemoteServiceRegisterFailsIfRegisterTwice(t *testing.T) { svc := NewRemoteService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) - err := svc.Register(&MyComp{}, []component.Option{}) + err := svc.Register(&MyComp{}, []component2.Option{}) assert.NoError(t, err) - err = svc.Register(&MyComp{}, []component.Option{}) + err = svc.Register(&MyComp{}, []component2.Option{}) assert.Contains(t, err.Error(), "remote: service already defined") } func TestRemoteServiceRegisterFailsIfNoRemoteMethods(t *testing.T) { svc := NewRemoteService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) - err := svc.Register(&NoHandlerRemoteComp{}, []component.Option{}) + err := svc.Register(&NoHandlerRemoteComp{}, []component2.Option{}) assert.Equal(t, errors.New("type NoHandlerRemoteComp has no exported methods of remote type"), err) } @@ -276,13 +276,13 @@ func TestRemoteServiceRemoteCall(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockSession := sessionmocks.NewMockSession(ctrl) - mockRPCClient := clustermocks.NewMockRPCClient(ctrl) + mockRPCClient := mocks.NewMockRPCClient(ctrl) sessionPool := sessionmocks.NewMockSessionPool(ctrl) router := router.New() svc := NewRemoteService(mockRPCClient, nil, nil, nil, nil, router, nil, nil, sessionPool, pipeline.NewHandlerHooks(), nil) assert.NotNil(t, svc) - msg := &message.Message{} + msg := &message2.Message{} ctx := context.Background() if table.server != nil { mockRPCClient.EXPECT().Call(ctx, protos.RPCType_Sys, rt, mockSession, msg, sv).Return(table.res, table.err) @@ -302,25 +302,25 @@ func TestRemoteServiceHandleRPCUser(t *testing.T) { assert.True(t, ok) assert.NotNil(t, m) rt := route.NewRoute("", uuid.New().String(), uuid.New().String()) - comp := &component.Remote{Receiver: reflect.ValueOf(tObj), Method: m, HasArgs: m.Type.NumIn() > 2} + comp := &component2.Remote{Receiver: reflect.ValueOf(tObj), Method: m, HasArgs: m.Type.NumIn() > 2} m, ok = reflect.TypeOf(tObj).MethodByName("RemoteErr") assert.True(t, ok) assert.NotNil(t, m) rtErr := route.NewRoute("", uuid.New().String(), uuid.New().String()) - compErr := &component.Remote{Receiver: reflect.ValueOf(tObj), Method: m, HasArgs: m.Type.NumIn() > 2} + compErr := &component2.Remote{Receiver: reflect.ValueOf(tObj), Method: m, HasArgs: m.Type.NumIn() > 2} m, ok = reflect.TypeOf(tObj).MethodByName("Remote2") assert.True(t, ok) assert.NotNil(t, m) rtStr := route.NewRoute("", uuid.New().String(), uuid.New().String()) - compStr := &component.Remote{Receiver: reflect.ValueOf(tObj), Method: m, HasArgs: m.Type.NumIn() > 2} + compStr := &component2.Remote{Receiver: reflect.ValueOf(tObj), Method: m, HasArgs: m.Type.NumIn() > 2} m, ok = reflect.TypeOf(tObj).MethodByName("RemoteRes") assert.True(t, ok) assert.NotNil(t, m) rtRes := route.NewRoute("", uuid.New().String(), uuid.New().String()) - compRes := &component.Remote{Receiver: reflect.ValueOf(tObj), Method: m, HasArgs: m.Type.NumIn() > 2, Type: reflect.TypeOf(&test.SomeStruct{B: "aa"})} + compRes := &component2.Remote{Receiver: reflect.ValueOf(tObj), Method: m, HasArgs: m.Type.NumIn() > 2, Type: reflect.TypeOf(&test.SomeStruct{B: "aa"})} b, err := proto.Marshal(&test.SomeStruct{B: "aa"}) assert.NoError(t, err) @@ -343,10 +343,10 @@ func TestRemoteServiceHandleRPCUser(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockSD := clustermocks.NewMockServiceDiscovery(ctrl) - mockRPCClient := clustermocks.NewMockRPCClient(ctrl) - mockRPCServer := clustermocks.NewMockRPCServer(ctrl) - messageEncoder := message.NewMessagesEncoder(false) + mockSD := mocks.NewMockServiceDiscovery(ctrl) + mockRPCClient := mocks.NewMockRPCClient(ctrl) + mockRPCServer := mocks.NewMockRPCServer(ctrl) + messageEncoder := message2.NewMessagesEncoder(false) router := router.New() sessionPool := session.NewSessionPool() svc := NewRemoteService(mockRPCClient, mockRPCServer, mockSD, packetEncoder, mockSerializer, router, messageEncoder, &cluster.Server{}, sessionPool, pipeline.NewHandlerHooks(), handlerPool) @@ -395,14 +395,14 @@ func TestRemoteServiceHandleRPCSys(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockSD := clustermocks.NewMockServiceDiscovery(ctrl) - mockRPCClient := clustermocks.NewMockRPCClient(ctrl) - mockRPCServer := clustermocks.NewMockRPCServer(ctrl) - messageEncoder := message.NewMessagesEncoder(false) + mockSD := mocks.NewMockServiceDiscovery(ctrl) + mockRPCClient := mocks.NewMockRPCClient(ctrl) + mockRPCServer := mocks.NewMockRPCServer(ctrl) + messageEncoder := message2.NewMessagesEncoder(false) router := router.New() sessionPool := session.NewSessionPool() handlerPool := NewHandlerPool() - handlerPool.handlers[rt.Short()] = &component.Handler{Receiver: reflect.ValueOf(tObj), Method: m, Type: m.Type.In(2)} + handlerPool.handlers[rt.Short()] = &component2.Handler{Receiver: reflect.ValueOf(tObj), Method: m, Type: m.Type.In(2)} svc := NewRemoteService(mockRPCClient, mockRPCServer, mockSD, packetEncoder, mockSerializer, router, messageEncoder, &cluster.Server{}, sessionPool, pipeline.NewHandlerHooks(), handlerPool) assert.NotNil(t, svc) @@ -426,15 +426,15 @@ func TestRemoteServiceRemoteProcess(t *testing.T) { rt := route.NewRoute("sv", "svc", "method") tables := []struct { - name string - msgType message.Type - remoteCallErr error + name string + msgType message2.Type + remoteCallErr error responseMIDErr error }{ - {"failed_remote_call", message.Request, errors.New("rpc failed"), nil}, - {"failed_response_mid", message.Request, nil, errors.New("err")}, - {"success_request", message.Request, nil, nil}, - {"success_notify", message.Notify, nil, nil}, + {"failed_remote_call", message2.Request, errors.New("rpc failed"), nil}, + {"failed_response_mid", message2.Request, nil, errors.New("err")}, + {"success_request", message2.Request, nil, nil}, + {"success_notify", message2.Notify, nil, nil}, } for _, table := range tables { @@ -442,7 +442,7 @@ func TestRemoteServiceRemoteProcess(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - expectedMsg := &message.Message{ + expectedMsg := &message2.Message{ ID: uint(rand.Int()), Type: table.msgType, Route: rt.Short(), @@ -452,10 +452,10 @@ func TestRemoteServiceRemoteProcess(t *testing.T) { packetEncoder := codec.NewPomeloPacketEncoder() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockSD := clustermocks.NewMockServiceDiscovery(ctrl) - mockRPCClient := clustermocks.NewMockRPCClient(ctrl) - mockRPCServer := clustermocks.NewMockRPCServer(ctrl) - messageEncoder := message.NewMessagesEncoder(false) + mockSD := mocks.NewMockServiceDiscovery(ctrl) + mockRPCClient := mocks.NewMockRPCClient(ctrl) + mockRPCServer := mocks.NewMockRPCServer(ctrl) + messageEncoder := message2.NewMessagesEncoder(false) router := router.New() sessionPool := session.NewSessionPool() mockSession := sessionmocks.NewMockSession(ctrl) @@ -467,7 +467,7 @@ func TestRemoteServiceRemoteProcess(t *testing.T) { if table.remoteCallErr != nil { mockAgent.EXPECT().AnswerWithError(ctx, expectedMsg.ID, gomock.Any()) - } else if expectedMsg.Type != message.Notify { + } else if expectedMsg.Type != message2.Notify { mockSession.EXPECT().ResponseMID(ctx, expectedMsg.ID, gomock.Any()).Return(table.responseMIDErr) } @@ -503,10 +503,10 @@ func TestRemoteServiceRPC(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() mockSerializer := serializemocks.NewMockSerializer(ctrl) - mockSD := clustermocks.NewMockServiceDiscovery(ctrl) - mockRPCClient := clustermocks.NewMockRPCClient(ctrl) - mockRPCServer := clustermocks.NewMockRPCServer(ctrl) - messageEncoder := message.NewMessagesEncoder(false) + mockSD := mocks.NewMockServiceDiscovery(ctrl) + mockRPCClient := mocks.NewMockRPCClient(ctrl) + mockRPCServer := mocks.NewMockRPCServer(ctrl) + messageEncoder := message2.NewMessagesEncoder(false) router := router.New() sessionPool := session.NewSessionPool() svc := NewRemoteService(mockRPCClient, mockRPCServer, mockSD, packetEncoder, mockSerializer, router, messageEncoder, &cluster.Server{}, sessionPool, pipeline.NewHandlerHooks(), nil) @@ -524,8 +524,8 @@ func TestRemoteServiceRPC(t *testing.T) { ctx := context.Background() if table.foundServer { expectedData, _ := proto.Marshal(table.arg) - expectedMsg := &message.Message{ - Type: message.Request, + expectedMsg := &message2.Message{ + Type: message2.Request, Route: rt.Short(), Data: expectedData, } diff --git a/service/util.go b/pkg/service/util.go similarity index 85% rename from service/util.go rename to pkg/service/util.go index 3cd95a9c..ec5a4e9c 100644 --- a/service/util.go +++ b/pkg/service/util.go @@ -23,21 +23,21 @@ package service import ( "context" "errors" + "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "reflect" "github.com/golang/protobuf/proto" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/logger/interfaces" - "github.com/topfreegames/pitaya/v2/pipeline" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/route" - "github.com/topfreegames/pitaya/v2/serialize" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/util" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/pipeline" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/route" + "github.com/topfreegames/pitaya/v3/pkg/serialize" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/util" ) var errInvalidMsg = errors.New("invalid message type provided") @@ -64,7 +64,7 @@ func unmarshalRemoteArg(remote *component.Remote, payload []byte) (interface{}, arg = reflect.New(remote.Type.Elem()).Interface() pb, ok := arg.(proto.Message) if !ok { - return nil, constants.ErrWrongValueType + return nil, constants2.ErrWrongValueType } err := proto.Unmarshal(payload, pb) if err != nil { @@ -113,7 +113,7 @@ func processHandlerMessage( if ctx == nil { ctx = context.Background() } - ctx = context.WithValue(ctx, constants.SessionCtxKey, session) + ctx = context.WithValue(ctx, constants2.SessionCtxKey, session) ctx = util.CtxWithDefaultLogger(ctx, rt.String(), session.UID()) msgType, err := getMsgType(msgTypeIface) @@ -121,7 +121,7 @@ func processHandlerMessage( return nil, e.NewError(err, e.ErrInternalCode) } - logger := ctx.Value(constants.LoggerCtxKey).(interfaces.Logger) + logger := ctx.Value(constants2.LoggerCtxKey).(interfaces.Logger) exit, err := handler.ValidateMessageType(msgType) if err != nil && exit { return nil, e.NewError(err, e.ErrBadRequestCode) diff --git a/service/util_test.go b/pkg/service/util_test.go similarity index 94% rename from service/util_test.go rename to pkg/service/util_test.go index c06e456c..68033b9d 100644 --- a/service/util_test.go +++ b/pkg/service/util_test.go @@ -24,6 +24,8 @@ import ( "context" "errors" "flag" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" "path/filepath" "reflect" "testing" @@ -32,19 +34,17 @@ import ( "github.com/golang/protobuf/proto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/helpers" - "github.com/topfreegames/pitaya/v2/pipeline" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/protos/test" - "github.com/topfreegames/pitaya/v2/serialize/mocks" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/pipeline" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/protos/test" + "github.com/topfreegames/pitaya/v3/pkg/serialize/mocks" ) var update = flag.Bool("update", false, "update .golden files") type TestType struct { - component.Base + component2.Base } func (t *TestType) HandlerNil(context.Context) {} @@ -86,7 +86,7 @@ func TestUnmarshalHandlerArg(t *testing.T) { m, ok := reflect.TypeOf(tObj).MethodByName(table.handlerName) assert.True(t, ok) assert.NotNil(t, m) - handler := &component.Handler{ + handler := &component2.Handler{ Method: m, IsRawArg: table.isRawArg, } @@ -133,20 +133,20 @@ func TestUnmarshalRemoteArg(t *testing.T) { } payload := helpers.ReadFile(t, gp) - remote := &component.Remote{ + remote := &component2.Remote{ Type: reflect.TypeOf(&test.SomeStruct{}), } arg, err := unmarshalRemoteArg(remote, payload) assert.NoError(t, err) - assert.Equal(t, table.arg, arg) + assert.True(t, proto.Equal(table.arg, arg.(*test.SomeStruct))) }) } } func TestUnmarshalRemoteArgErr(t *testing.T) { t.Parallel() - remote := &component.Remote{ + remote := &component2.Remote{ Type: reflect.TypeOf(&test.SomeStruct{}), } args, err := unmarshalRemoteArg(remote, []byte("arg")) diff --git a/session/fixtures/testSessionSetData_1.golden b/pkg/session/fixtures/testSessionSetData_1.golden similarity index 100% rename from session/fixtures/testSessionSetData_1.golden rename to pkg/session/fixtures/testSessionSetData_1.golden diff --git a/session/fixtures/testSessionSetData_2.golden b/pkg/session/fixtures/testSessionSetData_2.golden similarity index 100% rename from session/fixtures/testSessionSetData_2.golden rename to pkg/session/fixtures/testSessionSetData_2.golden diff --git a/session/fixtures/testSessionSetData_3.golden b/pkg/session/fixtures/testSessionSetData_3.golden similarity index 100% rename from session/fixtures/testSessionSetData_3.golden rename to pkg/session/fixtures/testSessionSetData_3.golden diff --git a/session/fixtures/testSessionSetData_4.golden b/pkg/session/fixtures/testSessionSetData_4.golden similarity index 100% rename from session/fixtures/testSessionSetData_4.golden rename to pkg/session/fixtures/testSessionSetData_4.golden diff --git a/session/fixtures/testSessionSetData_5.golden b/pkg/session/fixtures/testSessionSetData_5.golden similarity index 100% rename from session/fixtures/testSessionSetData_5.golden rename to pkg/session/fixtures/testSessionSetData_5.golden diff --git a/session/fixtures/testUpdateEncodedData_1.golden b/pkg/session/fixtures/testUpdateEncodedData_1.golden similarity index 100% rename from session/fixtures/testUpdateEncodedData_1.golden rename to pkg/session/fixtures/testUpdateEncodedData_1.golden diff --git a/session/fixtures/testUpdateEncodedData_2.golden b/pkg/session/fixtures/testUpdateEncodedData_2.golden similarity index 100% rename from session/fixtures/testUpdateEncodedData_2.golden rename to pkg/session/fixtures/testUpdateEncodedData_2.golden diff --git a/session/fixtures/testUpdateEncodedData_3.golden b/pkg/session/fixtures/testUpdateEncodedData_3.golden similarity index 100% rename from session/fixtures/testUpdateEncodedData_3.golden rename to pkg/session/fixtures/testUpdateEncodedData_3.golden diff --git a/session/fixtures/testUpdateEncodedData_4.golden b/pkg/session/fixtures/testUpdateEncodedData_4.golden similarity index 100% rename from session/fixtures/testUpdateEncodedData_4.golden rename to pkg/session/fixtures/testUpdateEncodedData_4.golden diff --git a/session/fixtures/testUpdateEncodedData_5.golden b/pkg/session/fixtures/testUpdateEncodedData_5.golden similarity index 100% rename from session/fixtures/testUpdateEncodedData_5.golden rename to pkg/session/fixtures/testUpdateEncodedData_5.golden diff --git a/session/mocks/session.go b/pkg/session/mocks/session.go similarity index 83% rename from session/mocks/session.go rename to pkg/session/mocks/session.go index 488b8797..80b4f5d4 100644 --- a/session/mocks/session.go +++ b/pkg/session/mocks/session.go @@ -1,43 +1,44 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/topfreegames/pitaya/v2/session (interfaces: Session,SessionPool) +// Source: github.com/topfreegames/pitaya/v3/pkg/session (interfaces: Session,SessionPool) // Package mocks is a generated GoMock package. package mocks import ( context "context" - gomock "github.com/golang/mock/gomock" - nats "github.com/nats-io/nats.go" - networkentity "github.com/topfreegames/pitaya/v2/networkentity" - session "github.com/topfreegames/pitaya/v2/session" net "net" reflect "reflect" + + gomock "github.com/golang/mock/gomock" + nats "github.com/nats-io/nats.go" + networkentity "github.com/topfreegames/pitaya/v3/pkg/networkentity" + session "github.com/topfreegames/pitaya/v3/pkg/session" ) -// MockSession is a mock of Session interface +// MockSession is a mock of Session interface. type MockSession struct { ctrl *gomock.Controller recorder *MockSessionMockRecorder } -// MockSessionMockRecorder is the mock recorder for MockSession +// MockSessionMockRecorder is the mock recorder for MockSession. type MockSessionMockRecorder struct { mock *MockSession } -// NewMockSession creates a new mock instance +// NewMockSession creates a new mock instance. func NewMockSession(ctrl *gomock.Controller) *MockSession { mock := &MockSession{ctrl: ctrl} mock.recorder = &MockSessionMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use +// EXPECT returns an object that allows the caller to indicate expected use. func (m *MockSession) EXPECT() *MockSessionMockRecorder { return m.recorder } -// Bind mocks base method +// Bind mocks base method. func (m *MockSession) Bind(arg0 context.Context, arg1 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Bind", arg0, arg1) @@ -45,37 +46,37 @@ func (m *MockSession) Bind(arg0 context.Context, arg1 string) error { return ret0 } -// Bind indicates an expected call of Bind +// Bind indicates an expected call of Bind. func (mr *MockSessionMockRecorder) Bind(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bind", reflect.TypeOf((*MockSession)(nil).Bind), arg0, arg1) } -// Clear mocks base method +// Clear mocks base method. func (m *MockSession) Clear() { m.ctrl.T.Helper() m.ctrl.Call(m, "Clear") } -// Clear indicates an expected call of Clear +// Clear indicates an expected call of Clear. func (mr *MockSessionMockRecorder) Clear() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Clear", reflect.TypeOf((*MockSession)(nil).Clear)) } -// Close mocks base method +// Close mocks base method. func (m *MockSession) Close() { m.ctrl.T.Helper() m.ctrl.Call(m, "Close") } -// Close indicates an expected call of Close +// Close indicates an expected call of Close. func (mr *MockSessionMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockSession)(nil).Close)) } -// Float32 mocks base method +// Float32 mocks base method. func (m *MockSession) Float32(arg0 string) float32 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Float32", arg0) @@ -83,13 +84,13 @@ func (m *MockSession) Float32(arg0 string) float32 { return ret0 } -// Float32 indicates an expected call of Float32 +// Float32 indicates an expected call of Float32. func (mr *MockSessionMockRecorder) Float32(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Float32", reflect.TypeOf((*MockSession)(nil).Float32), arg0) } -// Float64 mocks base method +// Float64 mocks base method. func (m *MockSession) Float64(arg0 string) float64 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Float64", arg0) @@ -97,13 +98,13 @@ func (m *MockSession) Float64(arg0 string) float64 { return ret0 } -// Float64 indicates an expected call of Float64 +// Float64 indicates an expected call of Float64. func (mr *MockSessionMockRecorder) Float64(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Float64", reflect.TypeOf((*MockSession)(nil).Float64), arg0) } -// Get mocks base method +// Get mocks base method. func (m *MockSession) Get(arg0 string) interface{} { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", arg0) @@ -111,13 +112,13 @@ func (m *MockSession) Get(arg0 string) interface{} { return ret0 } -// Get indicates an expected call of Get +// Get indicates an expected call of Get. func (mr *MockSessionMockRecorder) Get(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockSession)(nil).Get), arg0) } -// GetData mocks base method +// GetData mocks base method. func (m *MockSession) GetData() map[string]interface{} { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetData") @@ -125,13 +126,13 @@ func (m *MockSession) GetData() map[string]interface{} { return ret0 } -// GetData indicates an expected call of GetData +// GetData indicates an expected call of GetData. func (mr *MockSessionMockRecorder) GetData() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetData", reflect.TypeOf((*MockSession)(nil).GetData)) } -// GetDataEncoded mocks base method +// GetDataEncoded mocks base method. func (m *MockSession) GetDataEncoded() []byte { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetDataEncoded") @@ -139,13 +140,13 @@ func (m *MockSession) GetDataEncoded() []byte { return ret0 } -// GetDataEncoded indicates an expected call of GetDataEncoded +// GetDataEncoded indicates an expected call of GetDataEncoded. func (mr *MockSessionMockRecorder) GetDataEncoded() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDataEncoded", reflect.TypeOf((*MockSession)(nil).GetDataEncoded)) } -// GetHandshakeData mocks base method +// GetHandshakeData mocks base method. func (m *MockSession) GetHandshakeData() *session.HandshakeData { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetHandshakeData") @@ -153,13 +154,13 @@ func (m *MockSession) GetHandshakeData() *session.HandshakeData { return ret0 } -// GetHandshakeData indicates an expected call of GetHandshakeData +// GetHandshakeData indicates an expected call of GetHandshakeData. func (mr *MockSessionMockRecorder) GetHandshakeData() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetHandshakeData", reflect.TypeOf((*MockSession)(nil).GetHandshakeData)) } -// GetIsFrontend mocks base method +// GetIsFrontend mocks base method. func (m *MockSession) GetIsFrontend() bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetIsFrontend") @@ -167,13 +168,13 @@ func (m *MockSession) GetIsFrontend() bool { return ret0 } -// GetIsFrontend indicates an expected call of GetIsFrontend +// GetIsFrontend indicates an expected call of GetIsFrontend. func (mr *MockSessionMockRecorder) GetIsFrontend() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetIsFrontend", reflect.TypeOf((*MockSession)(nil).GetIsFrontend)) } -// GetOnCloseCallbacks mocks base method +// GetOnCloseCallbacks mocks base method. func (m *MockSession) GetOnCloseCallbacks() []func() { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetOnCloseCallbacks") @@ -181,13 +182,13 @@ func (m *MockSession) GetOnCloseCallbacks() []func() { return ret0 } -// GetOnCloseCallbacks indicates an expected call of GetOnCloseCallbacks +// GetOnCloseCallbacks indicates an expected call of GetOnCloseCallbacks. func (mr *MockSessionMockRecorder) GetOnCloseCallbacks() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOnCloseCallbacks", reflect.TypeOf((*MockSession)(nil).GetOnCloseCallbacks)) } -// GetSubscriptions mocks base method +// GetSubscriptions mocks base method. func (m *MockSession) GetSubscriptions() []*nats.Subscription { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSubscriptions") @@ -195,13 +196,13 @@ func (m *MockSession) GetSubscriptions() []*nats.Subscription { return ret0 } -// GetSubscriptions indicates an expected call of GetSubscriptions +// GetSubscriptions indicates an expected call of GetSubscriptions. func (mr *MockSessionMockRecorder) GetSubscriptions() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubscriptions", reflect.TypeOf((*MockSession)(nil).GetSubscriptions)) } -// HasKey mocks base method +// HasKey mocks base method. func (m *MockSession) HasKey(arg0 string) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HasKey", arg0) @@ -209,13 +210,13 @@ func (m *MockSession) HasKey(arg0 string) bool { return ret0 } -// HasKey indicates an expected call of HasKey +// HasKey indicates an expected call of HasKey. func (mr *MockSessionMockRecorder) HasKey(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HasKey", reflect.TypeOf((*MockSession)(nil).HasKey), arg0) } -// ID mocks base method +// ID mocks base method. func (m *MockSession) ID() int64 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ID") @@ -223,13 +224,13 @@ func (m *MockSession) ID() int64 { return ret0 } -// ID indicates an expected call of ID +// ID indicates an expected call of ID. func (mr *MockSessionMockRecorder) ID() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ID", reflect.TypeOf((*MockSession)(nil).ID)) } -// Int mocks base method +// Int mocks base method. func (m *MockSession) Int(arg0 string) int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Int", arg0) @@ -237,13 +238,13 @@ func (m *MockSession) Int(arg0 string) int { return ret0 } -// Int indicates an expected call of Int +// Int indicates an expected call of Int. func (mr *MockSessionMockRecorder) Int(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Int", reflect.TypeOf((*MockSession)(nil).Int), arg0) } -// Int16 mocks base method +// Int16 mocks base method. func (m *MockSession) Int16(arg0 string) int16 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Int16", arg0) @@ -251,13 +252,13 @@ func (m *MockSession) Int16(arg0 string) int16 { return ret0 } -// Int16 indicates an expected call of Int16 +// Int16 indicates an expected call of Int16. func (mr *MockSessionMockRecorder) Int16(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Int16", reflect.TypeOf((*MockSession)(nil).Int16), arg0) } -// Int32 mocks base method +// Int32 mocks base method. func (m *MockSession) Int32(arg0 string) int32 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Int32", arg0) @@ -265,13 +266,13 @@ func (m *MockSession) Int32(arg0 string) int32 { return ret0 } -// Int32 indicates an expected call of Int32 +// Int32 indicates an expected call of Int32. func (mr *MockSessionMockRecorder) Int32(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Int32", reflect.TypeOf((*MockSession)(nil).Int32), arg0) } -// Int64 mocks base method +// Int64 mocks base method. func (m *MockSession) Int64(arg0 string) int64 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Int64", arg0) @@ -279,13 +280,13 @@ func (m *MockSession) Int64(arg0 string) int64 { return ret0 } -// Int64 indicates an expected call of Int64 +// Int64 indicates an expected call of Int64. func (mr *MockSessionMockRecorder) Int64(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Int64", reflect.TypeOf((*MockSession)(nil).Int64), arg0) } -// Int8 mocks base method +// Int8 mocks base method. func (m *MockSession) Int8(arg0 string) int8 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Int8", arg0) @@ -293,13 +294,13 @@ func (m *MockSession) Int8(arg0 string) int8 { return ret0 } -// Int8 indicates an expected call of Int8 +// Int8 indicates an expected call of Int8. func (mr *MockSessionMockRecorder) Int8(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Int8", reflect.TypeOf((*MockSession)(nil).Int8), arg0) } -// Kick mocks base method +// Kick mocks base method. func (m *MockSession) Kick(arg0 context.Context) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Kick", arg0) @@ -307,13 +308,13 @@ func (m *MockSession) Kick(arg0 context.Context) error { return ret0 } -// Kick indicates an expected call of Kick +// Kick indicates an expected call of Kick. func (mr *MockSessionMockRecorder) Kick(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Kick", reflect.TypeOf((*MockSession)(nil).Kick), arg0) } -// OnClose mocks base method +// OnClose mocks base method. func (m *MockSession) OnClose(arg0 func()) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "OnClose", arg0) @@ -321,13 +322,13 @@ func (m *MockSession) OnClose(arg0 func()) error { return ret0 } -// OnClose indicates an expected call of OnClose +// OnClose indicates an expected call of OnClose. func (mr *MockSessionMockRecorder) OnClose(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnClose", reflect.TypeOf((*MockSession)(nil).OnClose), arg0) } -// Push mocks base method +// Push mocks base method. func (m *MockSession) Push(arg0 string, arg1 interface{}) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Push", arg0, arg1) @@ -335,13 +336,13 @@ func (m *MockSession) Push(arg0 string, arg1 interface{}) error { return ret0 } -// Push indicates an expected call of Push +// Push indicates an expected call of Push. func (mr *MockSessionMockRecorder) Push(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Push", reflect.TypeOf((*MockSession)(nil).Push), arg0, arg1) } -// PushToFront mocks base method +// PushToFront mocks base method. func (m *MockSession) PushToFront(arg0 context.Context) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PushToFront", arg0) @@ -349,13 +350,13 @@ func (m *MockSession) PushToFront(arg0 context.Context) error { return ret0 } -// PushToFront indicates an expected call of PushToFront +// PushToFront indicates an expected call of PushToFront. func (mr *MockSessionMockRecorder) PushToFront(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PushToFront", reflect.TypeOf((*MockSession)(nil).PushToFront), arg0) } -// RemoteAddr mocks base method +// RemoteAddr mocks base method. func (m *MockSession) RemoteAddr() net.Addr { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RemoteAddr") @@ -363,13 +364,13 @@ func (m *MockSession) RemoteAddr() net.Addr { return ret0 } -// RemoteAddr indicates an expected call of RemoteAddr +// RemoteAddr indicates an expected call of RemoteAddr. func (mr *MockSessionMockRecorder) RemoteAddr() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoteAddr", reflect.TypeOf((*MockSession)(nil).RemoteAddr)) } -// Remove mocks base method +// Remove mocks base method. func (m *MockSession) Remove(arg0 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Remove", arg0) @@ -377,13 +378,13 @@ func (m *MockSession) Remove(arg0 string) error { return ret0 } -// Remove indicates an expected call of Remove +// Remove indicates an expected call of Remove. func (mr *MockSessionMockRecorder) Remove(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockSession)(nil).Remove), arg0) } -// ResponseMID mocks base method +// ResponseMID mocks base method. func (m *MockSession) ResponseMID(arg0 context.Context, arg1 uint, arg2 interface{}, arg3 ...bool) error { m.ctrl.T.Helper() varargs := []interface{}{arg0, arg1, arg2} @@ -395,14 +396,14 @@ func (m *MockSession) ResponseMID(arg0 context.Context, arg1 uint, arg2 interfac return ret0 } -// ResponseMID indicates an expected call of ResponseMID +// ResponseMID indicates an expected call of ResponseMID. func (mr *MockSessionMockRecorder) ResponseMID(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{arg0, arg1, arg2}, arg3...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResponseMID", reflect.TypeOf((*MockSession)(nil).ResponseMID), varargs...) } -// Set mocks base method +// Set mocks base method. func (m *MockSession) Set(arg0 string, arg1 interface{}) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Set", arg0, arg1) @@ -410,13 +411,13 @@ func (m *MockSession) Set(arg0 string, arg1 interface{}) error { return ret0 } -// Set indicates an expected call of Set +// Set indicates an expected call of Set. func (mr *MockSessionMockRecorder) Set(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Set", reflect.TypeOf((*MockSession)(nil).Set), arg0, arg1) } -// SetData mocks base method +// SetData mocks base method. func (m *MockSession) SetData(arg0 map[string]interface{}) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetData", arg0) @@ -424,13 +425,13 @@ func (m *MockSession) SetData(arg0 map[string]interface{}) error { return ret0 } -// SetData indicates an expected call of SetData +// SetData indicates an expected call of SetData. func (mr *MockSessionMockRecorder) SetData(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetData", reflect.TypeOf((*MockSession)(nil).SetData), arg0) } -// SetDataEncoded mocks base method +// SetDataEncoded mocks base method. func (m *MockSession) SetDataEncoded(arg0 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetDataEncoded", arg0) @@ -438,73 +439,73 @@ func (m *MockSession) SetDataEncoded(arg0 []byte) error { return ret0 } -// SetDataEncoded indicates an expected call of SetDataEncoded +// SetDataEncoded indicates an expected call of SetDataEncoded. func (mr *MockSessionMockRecorder) SetDataEncoded(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDataEncoded", reflect.TypeOf((*MockSession)(nil).SetDataEncoded), arg0) } -// SetFrontendData mocks base method +// SetFrontendData mocks base method. func (m *MockSession) SetFrontendData(arg0 string, arg1 int64) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetFrontendData", arg0, arg1) } -// SetFrontendData indicates an expected call of SetFrontendData +// SetFrontendData indicates an expected call of SetFrontendData. func (mr *MockSessionMockRecorder) SetFrontendData(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFrontendData", reflect.TypeOf((*MockSession)(nil).SetFrontendData), arg0, arg1) } -// SetHandshakeData mocks base method +// SetHandshakeData mocks base method. func (m *MockSession) SetHandshakeData(arg0 *session.HandshakeData) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetHandshakeData", arg0) } -// SetHandshakeData indicates an expected call of SetHandshakeData +// SetHandshakeData indicates an expected call of SetHandshakeData. func (mr *MockSessionMockRecorder) SetHandshakeData(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetHandshakeData", reflect.TypeOf((*MockSession)(nil).SetHandshakeData), arg0) } -// SetIsFrontend mocks base method +// SetIsFrontend mocks base method. func (m *MockSession) SetIsFrontend(arg0 bool) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetIsFrontend", arg0) } -// SetIsFrontend indicates an expected call of SetIsFrontend +// SetIsFrontend indicates an expected call of SetIsFrontend. func (mr *MockSessionMockRecorder) SetIsFrontend(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetIsFrontend", reflect.TypeOf((*MockSession)(nil).SetIsFrontend), arg0) } -// SetOnCloseCallbacks mocks base method +// SetOnCloseCallbacks mocks base method. func (m *MockSession) SetOnCloseCallbacks(arg0 []func()) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetOnCloseCallbacks", arg0) } -// SetOnCloseCallbacks indicates an expected call of SetOnCloseCallbacks +// SetOnCloseCallbacks indicates an expected call of SetOnCloseCallbacks. func (mr *MockSessionMockRecorder) SetOnCloseCallbacks(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetOnCloseCallbacks", reflect.TypeOf((*MockSession)(nil).SetOnCloseCallbacks), arg0) } -// SetSubscriptions mocks base method +// SetSubscriptions mocks base method. func (m *MockSession) SetSubscriptions(arg0 []*nats.Subscription) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetSubscriptions", arg0) } -// SetSubscriptions indicates an expected call of SetSubscriptions +// SetSubscriptions indicates an expected call of SetSubscriptions. func (mr *MockSessionMockRecorder) SetSubscriptions(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubscriptions", reflect.TypeOf((*MockSession)(nil).SetSubscriptions), arg0) } -// String mocks base method +// String mocks base method. func (m *MockSession) String(arg0 string) string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "String", arg0) @@ -512,13 +513,13 @@ func (m *MockSession) String(arg0 string) string { return ret0 } -// String indicates an expected call of String +// String indicates an expected call of String. func (mr *MockSessionMockRecorder) String(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "String", reflect.TypeOf((*MockSession)(nil).String), arg0) } -// UID mocks base method +// UID mocks base method. func (m *MockSession) UID() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "UID") @@ -526,13 +527,13 @@ func (m *MockSession) UID() string { return ret0 } -// UID indicates an expected call of UID +// UID indicates an expected call of UID. func (mr *MockSessionMockRecorder) UID() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UID", reflect.TypeOf((*MockSession)(nil).UID)) } -// Uint mocks base method +// Uint mocks base method. func (m *MockSession) Uint(arg0 string) uint { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Uint", arg0) @@ -540,13 +541,13 @@ func (m *MockSession) Uint(arg0 string) uint { return ret0 } -// Uint indicates an expected call of Uint +// Uint indicates an expected call of Uint. func (mr *MockSessionMockRecorder) Uint(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Uint", reflect.TypeOf((*MockSession)(nil).Uint), arg0) } -// Uint16 mocks base method +// Uint16 mocks base method. func (m *MockSession) Uint16(arg0 string) uint16 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Uint16", arg0) @@ -554,13 +555,13 @@ func (m *MockSession) Uint16(arg0 string) uint16 { return ret0 } -// Uint16 indicates an expected call of Uint16 +// Uint16 indicates an expected call of Uint16. func (mr *MockSessionMockRecorder) Uint16(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Uint16", reflect.TypeOf((*MockSession)(nil).Uint16), arg0) } -// Uint32 mocks base method +// Uint32 mocks base method. func (m *MockSession) Uint32(arg0 string) uint32 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Uint32", arg0) @@ -568,13 +569,13 @@ func (m *MockSession) Uint32(arg0 string) uint32 { return ret0 } -// Uint32 indicates an expected call of Uint32 +// Uint32 indicates an expected call of Uint32. func (mr *MockSessionMockRecorder) Uint32(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Uint32", reflect.TypeOf((*MockSession)(nil).Uint32), arg0) } -// Uint64 mocks base method +// Uint64 mocks base method. func (m *MockSession) Uint64(arg0 string) uint64 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Uint64", arg0) @@ -582,13 +583,13 @@ func (m *MockSession) Uint64(arg0 string) uint64 { return ret0 } -// Uint64 indicates an expected call of Uint64 +// Uint64 indicates an expected call of Uint64. func (mr *MockSessionMockRecorder) Uint64(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Uint64", reflect.TypeOf((*MockSession)(nil).Uint64), arg0) } -// Uint8 mocks base method +// Uint8 mocks base method. func (m *MockSession) Uint8(arg0 string) byte { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Uint8", arg0) @@ -596,13 +597,13 @@ func (m *MockSession) Uint8(arg0 string) byte { return ret0 } -// Uint8 indicates an expected call of Uint8 +// Uint8 indicates an expected call of Uint8. func (mr *MockSessionMockRecorder) Uint8(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Uint8", reflect.TypeOf((*MockSession)(nil).Uint8), arg0) } -// Value mocks base method +// Value mocks base method. func (m *MockSession) Value(arg0 string) interface{} { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Value", arg0) @@ -610,48 +611,48 @@ func (m *MockSession) Value(arg0 string) interface{} { return ret0 } -// Value indicates an expected call of Value +// Value indicates an expected call of Value. func (mr *MockSessionMockRecorder) Value(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Value", reflect.TypeOf((*MockSession)(nil).Value), arg0) } -// MockSessionPool is a mock of SessionPool interface +// MockSessionPool is a mock of SessionPool interface. type MockSessionPool struct { ctrl *gomock.Controller recorder *MockSessionPoolMockRecorder } -// MockSessionPoolMockRecorder is the mock recorder for MockSessionPool +// MockSessionPoolMockRecorder is the mock recorder for MockSessionPool. type MockSessionPoolMockRecorder struct { mock *MockSessionPool } -// NewMockSessionPool creates a new mock instance +// NewMockSessionPool creates a new mock instance. func NewMockSessionPool(ctrl *gomock.Controller) *MockSessionPool { mock := &MockSessionPool{ctrl: ctrl} mock.recorder = &MockSessionPoolMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use +// EXPECT returns an object that allows the caller to indicate expected use. func (m *MockSessionPool) EXPECT() *MockSessionPoolMockRecorder { return m.recorder } -// CloseAll mocks base method +// CloseAll mocks base method. func (m *MockSessionPool) CloseAll() { m.ctrl.T.Helper() m.ctrl.Call(m, "CloseAll") } -// CloseAll indicates an expected call of CloseAll +// CloseAll indicates an expected call of CloseAll. func (mr *MockSessionPoolMockRecorder) CloseAll() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CloseAll", reflect.TypeOf((*MockSessionPool)(nil).CloseAll)) } -// GetSessionByID mocks base method +// GetSessionByID mocks base method. func (m *MockSessionPool) GetSessionByID(arg0 int64) session.Session { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSessionByID", arg0) @@ -659,13 +660,13 @@ func (m *MockSessionPool) GetSessionByID(arg0 int64) session.Session { return ret0 } -// GetSessionByID indicates an expected call of GetSessionByID +// GetSessionByID indicates an expected call of GetSessionByID. func (mr *MockSessionPoolMockRecorder) GetSessionByID(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSessionByID", reflect.TypeOf((*MockSessionPool)(nil).GetSessionByID), arg0) } -// GetSessionByUID mocks base method +// GetSessionByUID mocks base method. func (m *MockSessionPool) GetSessionByUID(arg0 string) session.Session { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSessionByUID", arg0) @@ -673,13 +674,13 @@ func (m *MockSessionPool) GetSessionByUID(arg0 string) session.Session { return ret0 } -// GetSessionByUID indicates an expected call of GetSessionByUID +// GetSessionByUID indicates an expected call of GetSessionByUID. func (mr *MockSessionPoolMockRecorder) GetSessionByUID(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSessionByUID", reflect.TypeOf((*MockSessionPool)(nil).GetSessionByUID), arg0) } -// GetSessionCloseCallbacks mocks base method +// GetSessionCloseCallbacks mocks base method. func (m *MockSessionPool) GetSessionCloseCallbacks() []func(session.Session) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSessionCloseCallbacks") @@ -687,13 +688,13 @@ func (m *MockSessionPool) GetSessionCloseCallbacks() []func(session.Session) { return ret0 } -// GetSessionCloseCallbacks indicates an expected call of GetSessionCloseCallbacks +// GetSessionCloseCallbacks indicates an expected call of GetSessionCloseCallbacks. func (mr *MockSessionPoolMockRecorder) GetSessionCloseCallbacks() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSessionCloseCallbacks", reflect.TypeOf((*MockSessionPool)(nil).GetSessionCloseCallbacks)) } -// GetSessionCount mocks base method +// GetSessionCount mocks base method. func (m *MockSessionPool) GetSessionCount() int64 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSessionCount") @@ -701,13 +702,13 @@ func (m *MockSessionPool) GetSessionCount() int64 { return ret0 } -// GetSessionCount indicates an expected call of GetSessionCount +// GetSessionCount indicates an expected call of GetSessionCount. func (mr *MockSessionPoolMockRecorder) GetSessionCount() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSessionCount", reflect.TypeOf((*MockSessionPool)(nil).GetSessionCount)) } -// NewSession mocks base method +// NewSession mocks base method. func (m *MockSessionPool) NewSession(arg0 networkentity.NetworkEntity, arg1 bool, arg2 ...string) session.Session { m.ctrl.T.Helper() varargs := []interface{}{arg0, arg1} @@ -719,44 +720,44 @@ func (m *MockSessionPool) NewSession(arg0 networkentity.NetworkEntity, arg1 bool return ret0 } -// NewSession indicates an expected call of NewSession +// NewSession indicates an expected call of NewSession. func (mr *MockSessionPoolMockRecorder) NewSession(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{arg0, arg1}, arg2...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewSession", reflect.TypeOf((*MockSessionPool)(nil).NewSession), varargs...) } -// OnAfterSessionBind mocks base method +// OnAfterSessionBind mocks base method. func (m *MockSessionPool) OnAfterSessionBind(arg0 func(context.Context, session.Session) error) { m.ctrl.T.Helper() m.ctrl.Call(m, "OnAfterSessionBind", arg0) } -// OnAfterSessionBind indicates an expected call of OnAfterSessionBind +// OnAfterSessionBind indicates an expected call of OnAfterSessionBind. func (mr *MockSessionPoolMockRecorder) OnAfterSessionBind(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnAfterSessionBind", reflect.TypeOf((*MockSessionPool)(nil).OnAfterSessionBind), arg0) } -// OnSessionBind mocks base method +// OnSessionBind mocks base method. func (m *MockSessionPool) OnSessionBind(arg0 func(context.Context, session.Session) error) { m.ctrl.T.Helper() m.ctrl.Call(m, "OnSessionBind", arg0) } -// OnSessionBind indicates an expected call of OnSessionBind +// OnSessionBind indicates an expected call of OnSessionBind. func (mr *MockSessionPoolMockRecorder) OnSessionBind(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnSessionBind", reflect.TypeOf((*MockSessionPool)(nil).OnSessionBind), arg0) } -// OnSessionClose mocks base method +// OnSessionClose mocks base method. func (m *MockSessionPool) OnSessionClose(arg0 func(session.Session)) { m.ctrl.T.Helper() m.ctrl.Call(m, "OnSessionClose", arg0) } -// OnSessionClose indicates an expected call of OnSessionClose +// OnSessionClose indicates an expected call of OnSessionClose. func (mr *MockSessionPoolMockRecorder) OnSessionClose(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnSessionClose", reflect.TypeOf((*MockSessionPool)(nil).OnSessionClose), arg0) diff --git a/session/session.go b/pkg/session/session.go similarity index 97% rename from session/session.go rename to pkg/session/session.go index c6b8a709..6ed5cae1 100644 --- a/session/session.go +++ b/pkg/session/session.go @@ -23,6 +23,7 @@ package session import ( "context" "encoding/json" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" "net" "reflect" "sync" @@ -31,10 +32,9 @@ import ( "github.com/golang/protobuf/proto" nats "github.com/nats-io/nats.go" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/networkentity" - "github.com/topfreegames/pitaya/v2/protos" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/networkentity" + "github.com/topfreegames/pitaya/v3/pkg/protos" ) type sessionPoolImpl struct { @@ -343,6 +343,10 @@ func (s *sessionImpl) SetData(data map[string]interface{}) error { s.Lock() defer s.Unlock() + if data == nil { + return constants2.ErrCantSetNilData + } + s.data = data return s.updateEncodedData() } @@ -374,11 +378,11 @@ func (s *sessionImpl) SetFrontendData(frontendID string, frontendSessionID int64 // Bind bind UID to current session func (s *sessionImpl) Bind(ctx context.Context, uid string) error { if uid == "" { - return constants.ErrIllegalUID + return constants2.ErrIllegalUID } if s.UID() != "" { - return constants.ErrSessionAlreadyBound + return constants2.ErrSessionAlreadyBound } s.uid = uid @@ -427,7 +431,7 @@ func (s *sessionImpl) Kick(ctx context.Context) error { // when the session is closed func (s *sessionImpl) OnClose(c func()) error { if !s.IsFrontend { - return constants.ErrOnCloseBackend + return constants2.ErrOnCloseBackend } s.OnCloseCallbacks = append(s.OnCloseCallbacks, c) return nil @@ -728,15 +732,15 @@ func (s *sessionImpl) Value(key string) interface{} { } func (s *sessionImpl) bindInFront(ctx context.Context) error { - return s.sendRequestToFront(ctx, constants.SessionBindRoute, false) + return s.sendRequestToFront(ctx, constants2.SessionBindRoute, false) } // PushToFront updates the session in the frontend func (s *sessionImpl) PushToFront(ctx context.Context) error { if s.IsFrontend { - return constants.ErrFrontSessionCantPushToFront + return constants2.ErrFrontSessionCantPushToFront } - return s.sendRequestToFront(ctx, constants.SessionPushRoute, true) + return s.sendRequestToFront(ctx, constants2.SessionPushRoute, true) } // Clear releases all data related to current session diff --git a/session/session_test.go b/pkg/session/session_test.go similarity index 98% rename from session/session_test.go rename to pkg/session/session_test.go index b9ef4f50..63a98fe5 100644 --- a/session/session_test.go +++ b/pkg/session/session_test.go @@ -26,6 +26,7 @@ import ( "errors" "flag" "fmt" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" "math/rand" "path/filepath" "testing" @@ -36,10 +37,9 @@ import ( "github.com/google/uuid" nats "github.com/nats-io/nats.go" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/helpers" - "github.com/topfreegames/pitaya/v2/networkentity/mocks" - "github.com/topfreegames/pitaya/v2/protos" + "github.com/topfreegames/pitaya/v3/pkg/helpers" + "github.com/topfreegames/pitaya/v3/pkg/networkentity/mocks" + "github.com/topfreegames/pitaya/v3/pkg/protos" ) var update = flag.Bool("update", false, "update .golden files") @@ -444,7 +444,7 @@ func TestSessionBindFailsWithoutUID(t *testing.T) { assert.NotNil(t, ss) err := ss.Bind(nil, "") - assert.Equal(t, constants.ErrIllegalUID, err) + assert.Equal(t, constants2.ErrIllegalUID, err) } func TestSessionBindFailsIfAlreadyBound(t *testing.T) { @@ -456,7 +456,7 @@ func TestSessionBindFailsIfAlreadyBound(t *testing.T) { assert.NotNil(t, ss) err := ss.Bind(nil, uuid.New().String()) - assert.Equal(t, constants.ErrSessionAlreadyBound, err) + assert.Equal(t, constants2.ErrSessionAlreadyBound, err) } func TestSessionBindRunsOnSessionBind(t *testing.T) { @@ -542,7 +542,7 @@ func TestSessionBindBackend(t *testing.T) { expectedRequestData, err := proto.Marshal(expectedSessionData) assert.NoError(t, err) - mockEntity.EXPECT().SendRequest(ctx, ss.frontendID, constants.SessionBindRoute, expectedRequestData).Return(&protos.Response{}, table.err) + mockEntity.EXPECT().SendRequest(ctx, ss.frontendID, constants2.SessionBindRoute, expectedRequestData).Return(&protos.Response{}, table.err) err = ss.Bind(ctx, uid) assert.Equal(t, table.err, err) @@ -567,7 +567,7 @@ func TestSessionOnCloseFailsIfBackend(t *testing.T) { assert.NotNil(t, ss) err := ss.OnClose(nil) - assert.Equal(t, constants.ErrOnCloseBackend, err) + assert.Equal(t, constants2.ErrOnCloseBackend, err) } func TestSessionOnClose(t *testing.T) { @@ -1299,7 +1299,7 @@ func TestSessionPushToFrontFailsIfFrontend(t *testing.T) { assert.NotNil(t, ss) err := ss.PushToFront(nil) - assert.Equal(t, constants.ErrFrontSessionCantPushToFront, err) + assert.Equal(t, constants2.ErrFrontSessionCantPushToFront, err) } func TestSessionPushToFront(t *testing.T) { @@ -1333,7 +1333,7 @@ func TestSessionPushToFront(t *testing.T) { expectedRequestData, err := proto.Marshal(expectedSessionData) assert.NoError(t, err) ctx := context.Background() - mockEntity.EXPECT().SendRequest(ctx, ss.frontendID, constants.SessionPushRoute, expectedRequestData).Return(nil, table.err) + mockEntity.EXPECT().SendRequest(ctx, ss.frontendID, constants2.SessionPushRoute, expectedRequestData).Return(nil, table.err) err = ss.PushToFront(ctx) assert.Equal(t, table.err, err) diff --git a/session/static.go b/pkg/session/static.go similarity index 100% rename from session/static.go rename to pkg/session/static.go diff --git a/static.go b/pkg/static.go similarity index 88% rename from static.go rename to pkg/static.go index 0620fe38..2dd7c07a 100644 --- a/static.go +++ b/pkg/static.go @@ -18,22 +18,23 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "context" + "github.com/topfreegames/pitaya/v3/pkg/cluster" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" + config2 "github.com/topfreegames/pitaya/v3/pkg/config" + "sync" "time" "github.com/golang/protobuf/proto" "github.com/spf13/viper" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/interfaces" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/router" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/worker" + "github.com/topfreegames/pitaya/v3/pkg/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/router" + "github.com/topfreegames/pitaya/v3/pkg/session" + "github.com/topfreegames/pitaya/v3/pkg/worker" ) var DefaultApp Pitaya @@ -51,7 +52,7 @@ func Configure( serverType, serverMode, serverMetadata, - config.NewConfig(cfgs...), + config2.NewConfig(cfgs...), ) DefaultApp = builder.Build() session.DefaultSessionPool = builder.SessionPool @@ -109,8 +110,8 @@ func AddRoute(serverType string, routingFunction router.RoutingFunc) error { return DefaultApp.AddRoute(serverType, routingFunction) } -func Shutdown() { - DefaultApp.Shutdown() +func Shutdown() *sync.WaitGroup { + return DefaultApp.Shutdown() } func StartWorker() { @@ -141,7 +142,7 @@ func ReliableRPC(routeStr string, metadata map[string]interface{}, reply, arg pr return DefaultApp.ReliableRPC(routeStr, metadata, reply, arg) } -func ReliableRPCWithOptions(routeStr string, metadata map[string]interface{}, reply, arg proto.Message, opts *config.EnqueueOpts) (jid string, err error) { +func ReliableRPCWithOptions(routeStr string, metadata map[string]interface{}, reply, arg proto.Message, opts *config2.EnqueueOpts) (jid string, err error) { return DefaultApp.ReliableRPCWithOptions(routeStr, metadata, reply, arg, opts) } @@ -197,11 +198,11 @@ func GroupDelete(ctx context.Context, groupName string) error { return DefaultApp.GroupDelete(ctx, groupName) } -func Register(c component.Component, options ...component.Option) { +func Register(c component2.Component, options ...component2.Option) { DefaultApp.Register(c, options...) } -func RegisterRemote(c component.Component, options ...component.Option) { +func RegisterRemote(c component2.Component, options ...component2.Option) { DefaultApp.RegisterRemote(c, options...) } diff --git a/static_test.go b/pkg/static_test.go similarity index 96% rename from static_test.go rename to pkg/static_test.go index 53f1e305..807172cb 100644 --- a/static_test.go +++ b/pkg/static_test.go @@ -18,11 +18,14 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( "context" "errors" + "github.com/topfreegames/pitaya/v3/pkg/cluster" + component2 "github.com/topfreegames/pitaya/v3/pkg/component" + "github.com/topfreegames/pitaya/v3/pkg/config" "testing" "time" @@ -31,16 +34,13 @@ import ( "github.com/google/uuid" "github.com/spf13/viper" "github.com/stretchr/testify/require" - "github.com/topfreegames/pitaya/v2/cluster" - "github.com/topfreegames/pitaya/v2/component" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/interfaces" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/mocks" - "github.com/topfreegames/pitaya/v2/session" - sessionmocks "github.com/topfreegames/pitaya/v2/session/mocks" - "github.com/topfreegames/pitaya/v2/worker" - workermocks "github.com/topfreegames/pitaya/v2/worker/mocks" + "github.com/topfreegames/pitaya/v3/pkg/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/mocks" + "github.com/topfreegames/pitaya/v3/pkg/session" + sessionmocks "github.com/topfreegames/pitaya/v3/pkg/session/mocks" + "github.com/topfreegames/pitaya/v3/pkg/worker" + workermocks "github.com/topfreegames/pitaya/v3/pkg/worker/mocks" "google.golang.org/protobuf/runtime/protoiface" ) @@ -802,8 +802,8 @@ func TestStaticGroupDelete(t *testing.T) { } func TestStaticRegister(t *testing.T) { - var c component.Component - options := []component.Option{} + var c component2.Component + options := []component2.Option{} ctrl := gomock.NewController(t) app := mocks.NewMockPitaya(ctrl) @@ -814,8 +814,8 @@ func TestStaticRegister(t *testing.T) { } func TestStaticRegisterRemote(t *testing.T) { - var c component.Component - options := []component.Option{} + var c component2.Component + options := []component2.Option{} ctrl := gomock.NewController(t) app := mocks.NewMockPitaya(ctrl) diff --git a/timer.go b/pkg/timer.go similarity index 97% rename from timer.go rename to pkg/timer.go index fce9e7aa..d6bbceb1 100644 --- a/timer.go +++ b/pkg/timer.go @@ -18,14 +18,14 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( + "github.com/topfreegames/pitaya/v3/pkg/constants" "math" "time" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/timer" + "github.com/topfreegames/pitaya/v3/pkg/timer" ) // NewTimer returns a new Timer containing a function that will be called diff --git a/timer/timer.go b/pkg/timer/timer.go similarity index 99% rename from timer/timer.go rename to pkg/timer/timer.go index e3abaf7f..f5c7ff84 100644 --- a/timer/timer.go +++ b/pkg/timer/timer.go @@ -25,7 +25,7 @@ import ( "sync/atomic" "time" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) var timerBacklog int diff --git a/timer/timer_test.go b/pkg/timer/timer_test.go similarity index 99% rename from timer/timer_test.go rename to pkg/timer/timer_test.go index 32af3243..f57c2ac2 100644 --- a/timer/timer_test.go +++ b/pkg/timer/timer_test.go @@ -25,7 +25,7 @@ import ( "time" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/helpers" + "github.com/topfreegames/pitaya/v3/pkg/helpers" ) type alwaysRunCondition struct{} diff --git a/timer_test.go b/pkg/timer_test.go similarity index 95% rename from timer_test.go rename to pkg/timer_test.go index 1617208e..0601960d 100644 --- a/timer_test.go +++ b/pkg/timer_test.go @@ -18,15 +18,15 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -package pitaya +package pkg import ( + "github.com/topfreegames/pitaya/v3/pkg/constants" "testing" "time" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/timer" + "github.com/topfreegames/pitaya/v3/pkg/timer" ) type MyCond struct{} diff --git a/tracing/jaeger/config.go b/pkg/tracing/jaeger/config.go similarity index 100% rename from tracing/jaeger/config.go rename to pkg/tracing/jaeger/config.go diff --git a/tracing/jaeger/config_test.go b/pkg/tracing/jaeger/config_test.go similarity index 100% rename from tracing/jaeger/config_test.go rename to pkg/tracing/jaeger/config_test.go diff --git a/tracing/log.go b/pkg/tracing/log.go similarity index 100% rename from tracing/log.go rename to pkg/tracing/log.go diff --git a/tracing/span.go b/pkg/tracing/span.go similarity index 90% rename from tracing/span.go rename to pkg/tracing/span.go index e6f044bd..cdb7946c 100644 --- a/tracing/span.go +++ b/pkg/tracing/span.go @@ -22,11 +22,11 @@ package tracing import ( "context" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" opentracing "github.com/opentracing/opentracing-go" - "github.com/topfreegames/pitaya/v2/constants" - pcontext "github.com/topfreegames/pitaya/v2/context" - "github.com/topfreegames/pitaya/v2/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger" ) func castValueToCarrier(val interface{}) (opentracing.TextMapCarrier, error) { @@ -44,7 +44,7 @@ func castValueToCarrier(val interface{}) (opentracing.TextMapCarrier, error) { } return opentracing.TextMapCarrier(carrier), nil } - return nil, constants.ErrInvalidSpanCarrier + return nil, constants2.ErrInvalidSpanCarrier } // ExtractSpan retrieves an opentracing span context from the given context.Context @@ -54,7 +54,7 @@ func ExtractSpan(ctx context.Context) (opentracing.SpanContext, error) { var spanCtx opentracing.SpanContext span := opentracing.SpanFromContext(ctx) if span == nil { - if s := pcontext.GetFromPropagateCtx(ctx, constants.SpanPropagateCtxKey); s != nil { + if s := pcontext.GetFromPropagateCtx(ctx, constants2.SpanPropagateCtxKey); s != nil { var err error carrier, err := castValueToCarrier(s) if err != nil { @@ -87,7 +87,7 @@ func InjectSpan(ctx context.Context) (context.Context, error) { if err != nil { return nil, err } - return pcontext.AddToPropagateCtx(ctx, constants.SpanPropagateCtxKey, spanData), nil + return pcontext.AddToPropagateCtx(ctx, constants2.SpanPropagateCtxKey, spanData), nil } // StartSpan starts a new span with a given parent context, operation name, tags and diff --git a/tracing/span_test.go b/pkg/tracing/span_test.go similarity index 91% rename from tracing/span_test.go rename to pkg/tracing/span_test.go index fa407005..d58fbb4a 100644 --- a/tracing/span_test.go +++ b/pkg/tracing/span_test.go @@ -23,15 +23,15 @@ package tracing import ( "context" "errors" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" "io" "os" "testing" opentracing "github.com/opentracing/opentracing-go" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/constants" - pcontext "github.com/topfreegames/pitaya/v2/context" - "github.com/topfreegames/pitaya/v2/tracing/jaeger" + "github.com/topfreegames/pitaya/v3/pkg/tracing/jaeger" ) var closer io.Closer @@ -83,7 +83,7 @@ func TestExtractSpanInjectedSpan(t *testing.T) { tracer := opentracing.GlobalTracer() err := tracer.Inject(span.Context(), opentracing.TextMap, spanData) assert.NoError(t, err) - ctx := pcontext.AddToPropagateCtx(context.Background(), constants.SpanPropagateCtxKey, spanData) + ctx := pcontext.AddToPropagateCtx(context.Background(), constants2.SpanPropagateCtxKey, spanData) spanCtx, err := ExtractSpan(ctx) assert.NoError(t, err) @@ -97,9 +97,9 @@ func TestExtractSpanNoSpan(t *testing.T) { } func TestExtractSpanBadInjected(t *testing.T) { - ctx := pcontext.AddToPropagateCtx(context.Background(), constants.SpanPropagateCtxKey, []byte("nope")) + ctx := pcontext.AddToPropagateCtx(context.Background(), constants2.SpanPropagateCtxKey, []byte("nope")) spanCtx, err := ExtractSpan(ctx) - assert.Equal(t, constants.ErrInvalidSpanCarrier, err) + assert.Equal(t, constants2.ErrInvalidSpanCarrier, err) assert.Nil(t, spanCtx) } @@ -116,7 +116,7 @@ func TestInjectSpan(t *testing.T) { ctx, err := InjectSpan(origCtx) assert.NoError(t, err) assert.NotEqual(t, origCtx, ctx) - encodedCtx := pcontext.GetFromPropagateCtx(ctx, constants.SpanPropagateCtxKey) + encodedCtx := pcontext.GetFromPropagateCtx(ctx, constants2.SpanPropagateCtxKey) assert.NotNil(t, encodedCtx) } diff --git a/util/compression/compression.go b/pkg/util/compression/compression.go similarity index 100% rename from util/compression/compression.go rename to pkg/util/compression/compression.go diff --git a/util/compression/compression_test.go b/pkg/util/compression/compression_test.go similarity index 96% rename from util/compression/compression_test.go rename to pkg/util/compression/compression_test.go index 19c1ee13..ab9f9a29 100644 --- a/util/compression/compression_test.go +++ b/pkg/util/compression/compression_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/topfreegames/pitaya/v2/helpers" + "github.com/topfreegames/pitaya/v3/pkg/helpers" ) var update = flag.Bool("update", false, "update .golden files") diff --git a/util/compression/fixtures/compression_deflate_test_1.golden b/pkg/util/compression/fixtures/compression_deflate_test_1.golden similarity index 100% rename from util/compression/fixtures/compression_deflate_test_1.golden rename to pkg/util/compression/fixtures/compression_deflate_test_1.golden diff --git a/util/compression/fixtures/compression_deflate_test_2.golden b/pkg/util/compression/fixtures/compression_deflate_test_2.golden similarity index 100% rename from util/compression/fixtures/compression_deflate_test_2.golden rename to pkg/util/compression/fixtures/compression_deflate_test_2.golden diff --git a/util/compression/fixtures/compression_deflate_test_3.golden b/pkg/util/compression/fixtures/compression_deflate_test_3.golden similarity index 100% rename from util/compression/fixtures/compression_deflate_test_3.golden rename to pkg/util/compression/fixtures/compression_deflate_test_3.golden diff --git a/util/fixtures/gob_encode_test_1.golden b/pkg/util/fixtures/gob_encode_test_1.golden similarity index 100% rename from util/fixtures/gob_encode_test_1.golden rename to pkg/util/fixtures/gob_encode_test_1.golden diff --git a/util/fixtures/gob_encode_test_2.golden b/pkg/util/fixtures/gob_encode_test_2.golden similarity index 100% rename from util/fixtures/gob_encode_test_2.golden rename to pkg/util/fixtures/gob_encode_test_2.golden diff --git a/util/fixtures/gob_encode_test_3.golden b/pkg/util/fixtures/gob_encode_test_3.golden similarity index 100% rename from util/fixtures/gob_encode_test_3.golden rename to pkg/util/fixtures/gob_encode_test_3.golden diff --git a/util/util.go b/pkg/util/util.go similarity index 84% rename from util/util.go rename to pkg/util/util.go index bd94de09..23ef0b08 100644 --- a/util/util.go +++ b/pkg/util/util.go @@ -25,22 +25,22 @@ import ( "errors" "fmt" "github.com/nats-io/nuid" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + constants2 "github.com/topfreegames/pitaya/v3/pkg/constants" + pcontext "github.com/topfreegames/pitaya/v3/pkg/context" + e "github.com/topfreegames/pitaya/v3/pkg/errors" "os" "reflect" "runtime/debug" "strconv" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - pcontext "github.com/topfreegames/pitaya/v2/context" - e "github.com/topfreegames/pitaya/v2/errors" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/logger/interfaces" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/serialize" - "github.com/topfreegames/pitaya/v2/serialize/json" - "github.com/topfreegames/pitaya/v2/serialize/protobuf" - "github.com/topfreegames/pitaya/v2/tracing" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/serialize" + "github.com/topfreegames/pitaya/v3/pkg/serialize/json" + "github.com/topfreegames/pitaya/v3/pkg/serialize/protobuf" + "github.com/topfreegames/pitaya/v3/pkg/tracing" opentracing "github.com/opentracing/opentracing-go" ) @@ -51,7 +51,7 @@ func getLoggerFromArgs(args []reflect.Value) interfaces.Logger { continue } if ctx, ok := a.Interface().(context.Context); ok { - logVal := ctx.Value(constants.LoggerCtxKey) + logVal := ctx.Value(constants2.LoggerCtxKey) if logVal != nil { log := logVal.(interfaces.Logger) return log @@ -88,7 +88,7 @@ func Pcall(method reflect.Method, args []reflect.Value) (rets interface{}, err e } else if !r[0].IsNil() { rets = r[0].Interface() } else { - err = constants.ErrReplyShouldBeNotNull + err = constants2.ErrReplyShouldBeNotNull } } return @@ -171,7 +171,7 @@ func ConvertProtoToMessageType(protoMsgType protos.MsgType) message.Type { // If using logrus, userId, route and requestId will be added as fields. // Otherwise the pitaya logger will be used as it is. func CtxWithDefaultLogger(ctx context.Context, route, userID string) context.Context { - requestID := pcontext.GetFromPropagateCtx(ctx, constants.RequestIDKey) + requestID := pcontext.GetFromPropagateCtx(ctx, constants2.RequestIDKey) if rID, ok := requestID.(string); ok { if rID == "" { requestID = nuid.New() @@ -187,7 +187,7 @@ func CtxWithDefaultLogger(ctx context.Context, route, userID string) context.Con }, ) - return context.WithValue(ctx, constants.LoggerCtxKey, defaultLogger) + return context.WithValue(ctx, constants2.LoggerCtxKey, defaultLogger) } // StartSpanFromRequest starts a tracing span from the request @@ -201,9 +201,9 @@ func StartSpanFromRequest( tags := opentracing.Tags{ "local.id": serverID, "span.kind": "server", - "peer.id": pcontext.GetFromPropagateCtx(ctx, constants.PeerIDKey), - "peer.service": pcontext.GetFromPropagateCtx(ctx, constants.PeerServiceKey), - "request.id": pcontext.GetFromPropagateCtx(ctx, constants.RequestIDKey), + "peer.id": pcontext.GetFromPropagateCtx(ctx, constants2.PeerIDKey), + "peer.service": pcontext.GetFromPropagateCtx(ctx, constants2.PeerServiceKey), + "request.id": pcontext.GetFromPropagateCtx(ctx, constants2.RequestIDKey), } parent, err := tracing.ExtractSpan(ctx) if err != nil { @@ -220,7 +220,7 @@ func GetContextFromRequest(req *protos.Request, serverID string) (context.Contex return nil, err } if ctx == nil { - return nil, constants.ErrNoContextFound + return nil, constants2.ErrNoContextFound } ctx = CtxWithDefaultLogger(ctx, req.GetMsg().GetRoute(), "") return ctx, nil diff --git a/util/util_test.go b/pkg/util/util_test.go similarity index 96% rename from util/util_test.go rename to pkg/util/util_test.go index e2e7bce5..7c86c2e2 100644 --- a/util/util_test.go +++ b/pkg/util/util_test.go @@ -24,16 +24,16 @@ import ( "errors" "flag" "fmt" + "github.com/topfreegames/pitaya/v3/pkg/conn/message" + "github.com/topfreegames/pitaya/v3/pkg/constants" "path/filepath" "reflect" "testing" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" - "github.com/topfreegames/pitaya/v2/conn/message" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/protos" - "github.com/topfreegames/pitaya/v2/serialize/mocks" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/serialize/mocks" ) var update = flag.Bool("update", false, "update .golden files") diff --git a/worker/constants.go b/pkg/worker/constants.go similarity index 100% rename from worker/constants.go rename to pkg/worker/constants.go diff --git a/worker/mocks/rpc_job.go b/pkg/worker/mocks/rpc_job.go similarity index 96% rename from worker/mocks/rpc_job.go rename to pkg/worker/mocks/rpc_job.go index 7655fadd..1365a69b 100644 --- a/worker/mocks/rpc_job.go +++ b/pkg/worker/mocks/rpc_job.go @@ -1,5 +1,5 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/topfreegames/pitaya/v2/worker (interfaces: RPCJob) +// Source: github.com/topfreegames/pitaya/v3/pkg/worker (interfaces: RPCJob) // Package mocks is a generated GoMock package. package mocks diff --git a/worker/models.go b/pkg/worker/models.go similarity index 100% rename from worker/models.go rename to pkg/worker/models.go diff --git a/worker/report.go b/pkg/worker/report.go similarity index 94% rename from worker/report.go rename to pkg/worker/report.go index 117a218f..8778d633 100644 --- a/worker/report.go +++ b/pkg/worker/report.go @@ -4,8 +4,8 @@ import ( "strconv" "time" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/metrics" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/metrics" workers "github.com/topfreegames/go-workers" ) diff --git a/worker/report_test.go b/pkg/worker/report_test.go similarity index 94% rename from worker/report_test.go rename to pkg/worker/report_test.go index ef9c5510..faaa1e82 100644 --- a/worker/report_test.go +++ b/pkg/worker/report_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/golang/mock/gomock" - "github.com/topfreegames/pitaya/v2/metrics" - "github.com/topfreegames/pitaya/v2/metrics/mocks" + "github.com/topfreegames/pitaya/v3/pkg/metrics" + "github.com/topfreegames/pitaya/v3/pkg/metrics/mocks" ) func TestReportJobsRetry(t *testing.T) { diff --git a/worker/rpc_job.go b/pkg/worker/rpc_job.go similarity index 100% rename from worker/rpc_job.go rename to pkg/worker/rpc_job.go diff --git a/worker/worker.go b/pkg/worker/worker.go similarity index 96% rename from worker/worker.go rename to pkg/worker/worker.go index be52364e..fdef4c00 100644 --- a/worker/worker.go +++ b/pkg/worker/worker.go @@ -23,14 +23,14 @@ package worker import ( "context" "encoding/json" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/constants" "os" "github.com/golang/protobuf/proto" workers "github.com/topfreegames/go-workers" - "github.com/topfreegames/pitaya/v2/config" - "github.com/topfreegames/pitaya/v2/constants" - "github.com/topfreegames/pitaya/v2/logger" - "github.com/topfreegames/pitaya/v2/logger/interfaces" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger/interfaces" ) // Worker executes RPCs with retry and backoff time diff --git a/worker/worker_test.go b/pkg/worker/worker_test.go similarity index 98% rename from worker/worker_test.go rename to pkg/worker/worker_test.go index 21ea244a..7e3a4e1b 100644 --- a/worker/worker_test.go +++ b/pkg/worker/worker_test.go @@ -8,7 +8,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" workers "github.com/topfreegames/go-workers" - "github.com/topfreegames/pitaya/v2/worker/mocks" + "github.com/topfreegames/pitaya/v3/pkg/worker/mocks" ) type fakeProtoMessage struct { diff --git a/protos/bind.pb.go b/protos/bind.pb.go deleted file mode 100644 index e76aa796..00000000 --- a/protos/bind.pb.go +++ /dev/null @@ -1,81 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: bind.proto - -package protos - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type BindMsg struct { - Uid string `protobuf:"bytes,1,opt,name=uid" json:"uid,omitempty"` - Fid string `protobuf:"bytes,2,opt,name=fid" json:"fid,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BindMsg) Reset() { *m = BindMsg{} } -func (m *BindMsg) String() string { return proto.CompactTextString(m) } -func (*BindMsg) ProtoMessage() {} -func (*BindMsg) Descriptor() ([]byte, []int) { - return fileDescriptor_bind_9cf772af172ead7d, []int{0} -} -func (m *BindMsg) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_BindMsg.Unmarshal(m, b) -} -func (m *BindMsg) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_BindMsg.Marshal(b, m, deterministic) -} -func (dst *BindMsg) XXX_Merge(src proto.Message) { - xxx_messageInfo_BindMsg.Merge(dst, src) -} -func (m *BindMsg) XXX_Size() int { - return xxx_messageInfo_BindMsg.Size(m) -} -func (m *BindMsg) XXX_DiscardUnknown() { - xxx_messageInfo_BindMsg.DiscardUnknown(m) -} - -var xxx_messageInfo_BindMsg proto.InternalMessageInfo - -func (m *BindMsg) GetUid() string { - if m != nil { - return m.Uid - } - return "" -} - -func (m *BindMsg) GetFid() string { - if m != nil { - return m.Fid - } - return "" -} - -func init() { - proto.RegisterType((*BindMsg)(nil), "protos.BindMsg") -} - -func init() { proto.RegisterFile("bind.proto", fileDescriptor_bind_9cf772af172ead7d) } - -var fileDescriptor_bind_9cf772af172ead7d = []byte{ - // 83 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4a, 0xca, 0xcc, 0x4b, - 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x53, 0xc5, 0x4a, 0xba, 0x5c, 0xec, 0x4e, - 0x99, 0x79, 0x29, 0xbe, 0xc5, 0xe9, 0x42, 0x02, 0x5c, 0xcc, 0xa5, 0x99, 0x29, 0x12, 0x8c, 0x0a, - 0x8c, 0x1a, 0x9c, 0x41, 0x20, 0x26, 0x48, 0x24, 0x2d, 0x33, 0x45, 0x82, 0x09, 0x22, 0x92, 0x96, - 0x99, 0x92, 0x04, 0xd1, 0x66, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0xce, 0x99, 0xf6, 0x32, 0x4b, - 0x00, 0x00, 0x00, -} diff --git a/protos/doc.pb.go b/protos/doc.pb.go deleted file mode 100644 index 6df95857..00000000 --- a/protos/doc.pb.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: doc.proto - -package protos - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Doc struct { - Doc string `protobuf:"bytes,1,opt,name=doc" json:"doc,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Doc) Reset() { *m = Doc{} } -func (m *Doc) String() string { return proto.CompactTextString(m) } -func (*Doc) ProtoMessage() {} -func (*Doc) Descriptor() ([]byte, []int) { - return fileDescriptor_doc_ddb39afaa46ee6d6, []int{0} -} -func (m *Doc) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Doc.Unmarshal(m, b) -} -func (m *Doc) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Doc.Marshal(b, m, deterministic) -} -func (dst *Doc) XXX_Merge(src proto.Message) { - xxx_messageInfo_Doc.Merge(dst, src) -} -func (m *Doc) XXX_Size() int { - return xxx_messageInfo_Doc.Size(m) -} -func (m *Doc) XXX_DiscardUnknown() { - xxx_messageInfo_Doc.DiscardUnknown(m) -} - -var xxx_messageInfo_Doc proto.InternalMessageInfo - -func (m *Doc) GetDoc() string { - if m != nil { - return m.Doc - } - return "" -} - -func init() { - proto.RegisterType((*Doc)(nil), "protos.Doc") -} - -func init() { proto.RegisterFile("doc.proto", fileDescriptor_doc_ddb39afaa46ee6d6) } - -var fileDescriptor_doc_ddb39afaa46ee6d6 = []byte{ - // 66 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4c, 0xc9, 0x4f, 0xd6, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x53, 0xc5, 0x4a, 0xe2, 0x5c, 0xcc, 0x2e, 0xf9, - 0xc9, 0x42, 0x02, 0x5c, 0xcc, 0x29, 0xf9, 0xc9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x20, - 0x66, 0x12, 0x44, 0x81, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x98, 0xdb, 0x15, 0x9b, 0x34, 0x00, - 0x00, 0x00, -} diff --git a/protos/docmsg.pb.go b/protos/docmsg.pb.go deleted file mode 100644 index f83140bb..00000000 --- a/protos/docmsg.pb.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: docmsg.proto - -package protos - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type DocMsg struct { - GetProtos bool `protobuf:"varint,1,opt,name=getProtos" json:"getProtos,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DocMsg) Reset() { *m = DocMsg{} } -func (m *DocMsg) String() string { return proto.CompactTextString(m) } -func (*DocMsg) ProtoMessage() {} -func (*DocMsg) Descriptor() ([]byte, []int) { - return fileDescriptor_docmsg_6d699a2b0ab5525e, []int{0} -} -func (m *DocMsg) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DocMsg.Unmarshal(m, b) -} -func (m *DocMsg) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DocMsg.Marshal(b, m, deterministic) -} -func (dst *DocMsg) XXX_Merge(src proto.Message) { - xxx_messageInfo_DocMsg.Merge(dst, src) -} -func (m *DocMsg) XXX_Size() int { - return xxx_messageInfo_DocMsg.Size(m) -} -func (m *DocMsg) XXX_DiscardUnknown() { - xxx_messageInfo_DocMsg.DiscardUnknown(m) -} - -var xxx_messageInfo_DocMsg proto.InternalMessageInfo - -func (m *DocMsg) GetGetProtos() bool { - if m != nil { - return m.GetProtos - } - return false -} - -func init() { - proto.RegisterType((*DocMsg)(nil), "protos.DocMsg") -} - -func init() { proto.RegisterFile("docmsg.proto", fileDescriptor_docmsg_6d699a2b0ab5525e) } - -var fileDescriptor_docmsg_6d699a2b0ab5525e = []byte{ - // 75 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x49, 0xc9, 0x4f, 0xce, - 0x2d, 0x4e, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x53, 0xc5, 0x4a, 0x6a, 0x5c, - 0x6c, 0x2e, 0xf9, 0xc9, 0xbe, 0xc5, 0xe9, 0x42, 0x32, 0x5c, 0x9c, 0xe9, 0xa9, 0x25, 0x01, 0x60, - 0x61, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x8e, 0x20, 0x84, 0x40, 0x12, 0x44, 0xbd, 0x31, 0x20, 0x00, - 0x00, 0xff, 0xff, 0x77, 0x5a, 0xd8, 0xbe, 0x46, 0x00, 0x00, 0x00, -} diff --git a/protos/error.pb.go b/protos/error.pb.go deleted file mode 100644 index 7898367e..00000000 --- a/protos/error.pb.go +++ /dev/null @@ -1,94 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: error.proto - -package protos - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Error struct { - Code string `protobuf:"bytes,1,opt,name=code" json:"code,omitempty"` - Msg string `protobuf:"bytes,2,opt,name=msg" json:"msg,omitempty"` - Metadata map[string]string `protobuf:"bytes,3,rep,name=metadata" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Error) Reset() { *m = Error{} } -func (m *Error) String() string { return proto.CompactTextString(m) } -func (*Error) ProtoMessage() {} -func (*Error) Descriptor() ([]byte, []int) { - return fileDescriptor_error_ea2c1b3dd908475b, []int{0} -} -func (m *Error) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Error.Unmarshal(m, b) -} -func (m *Error) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Error.Marshal(b, m, deterministic) -} -func (dst *Error) XXX_Merge(src proto.Message) { - xxx_messageInfo_Error.Merge(dst, src) -} -func (m *Error) XXX_Size() int { - return xxx_messageInfo_Error.Size(m) -} -func (m *Error) XXX_DiscardUnknown() { - xxx_messageInfo_Error.DiscardUnknown(m) -} - -var xxx_messageInfo_Error proto.InternalMessageInfo - -func (m *Error) GetCode() string { - if m != nil { - return m.Code - } - return "" -} - -func (m *Error) GetMsg() string { - if m != nil { - return m.Msg - } - return "" -} - -func (m *Error) GetMetadata() map[string]string { - if m != nil { - return m.Metadata - } - return nil -} - -func init() { - proto.RegisterType((*Error)(nil), "protos.Error") - proto.RegisterMapType((map[string]string)(nil), "protos.Error.MetadataEntry") -} - -func init() { proto.RegisterFile("error.proto", fileDescriptor_error_ea2c1b3dd908475b) } - -var fileDescriptor_error_ea2c1b3dd908475b = []byte{ - // 153 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x4e, 0x2d, 0x2a, 0xca, - 0x2f, 0xd2, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x53, 0xc5, 0x4a, 0x8b, 0x19, 0xb9, - 0x58, 0x5d, 0x41, 0xe2, 0x42, 0x42, 0x5c, 0x2c, 0xc9, 0xf9, 0x29, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, - 0x1a, 0x9c, 0x41, 0x60, 0xb6, 0x90, 0x00, 0x17, 0x73, 0x6e, 0x71, 0xba, 0x04, 0x13, 0x58, 0x08, - 0xc4, 0x14, 0x32, 0xe7, 0xe2, 0xc8, 0x4d, 0x2d, 0x49, 0x4c, 0x49, 0x2c, 0x49, 0x94, 0x60, 0x56, - 0x60, 0xd6, 0xe0, 0x36, 0x92, 0x86, 0x98, 0x58, 0xac, 0x07, 0x36, 0x46, 0xcf, 0x17, 0x2a, 0xeb, - 0x9a, 0x57, 0x52, 0x54, 0x19, 0x04, 0x57, 0x2c, 0x65, 0xcd, 0xc5, 0x8b, 0x22, 0x05, 0x32, 0x3b, - 0x3b, 0xb5, 0x12, 0x6a, 0x1d, 0x88, 0x29, 0x24, 0xc2, 0xc5, 0x5a, 0x96, 0x98, 0x53, 0x9a, 0x0a, - 0xb5, 0x0f, 0xc2, 0xb1, 0x62, 0xb2, 0x60, 0x4c, 0x82, 0xb8, 0xd6, 0x18, 0x10, 0x00, 0x00, 0xff, - 0xff, 0xb9, 0xd5, 0x83, 0x89, 0xc3, 0x00, 0x00, 0x00, -} diff --git a/protos/kick.pb.go b/protos/kick.pb.go deleted file mode 100644 index 79f5b2f4..00000000 --- a/protos/kick.pb.go +++ /dev/null @@ -1,113 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: kick.proto - -package protos - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type KickMsg struct { - UserId string `protobuf:"bytes,1,opt,name=userId" json:"userId,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *KickMsg) Reset() { *m = KickMsg{} } -func (m *KickMsg) String() string { return proto.CompactTextString(m) } -func (*KickMsg) ProtoMessage() {} -func (*KickMsg) Descriptor() ([]byte, []int) { - return fileDescriptor_kick_71de7c6289e550fd, []int{0} -} -func (m *KickMsg) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_KickMsg.Unmarshal(m, b) -} -func (m *KickMsg) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_KickMsg.Marshal(b, m, deterministic) -} -func (dst *KickMsg) XXX_Merge(src proto.Message) { - xxx_messageInfo_KickMsg.Merge(dst, src) -} -func (m *KickMsg) XXX_Size() int { - return xxx_messageInfo_KickMsg.Size(m) -} -func (m *KickMsg) XXX_DiscardUnknown() { - xxx_messageInfo_KickMsg.DiscardUnknown(m) -} - -var xxx_messageInfo_KickMsg proto.InternalMessageInfo - -func (m *KickMsg) GetUserId() string { - if m != nil { - return m.UserId - } - return "" -} - -type KickAnswer struct { - Kicked bool `protobuf:"varint,1,opt,name=kicked" json:"kicked,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *KickAnswer) Reset() { *m = KickAnswer{} } -func (m *KickAnswer) String() string { return proto.CompactTextString(m) } -func (*KickAnswer) ProtoMessage() {} -func (*KickAnswer) Descriptor() ([]byte, []int) { - return fileDescriptor_kick_71de7c6289e550fd, []int{1} -} -func (m *KickAnswer) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_KickAnswer.Unmarshal(m, b) -} -func (m *KickAnswer) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_KickAnswer.Marshal(b, m, deterministic) -} -func (dst *KickAnswer) XXX_Merge(src proto.Message) { - xxx_messageInfo_KickAnswer.Merge(dst, src) -} -func (m *KickAnswer) XXX_Size() int { - return xxx_messageInfo_KickAnswer.Size(m) -} -func (m *KickAnswer) XXX_DiscardUnknown() { - xxx_messageInfo_KickAnswer.DiscardUnknown(m) -} - -var xxx_messageInfo_KickAnswer proto.InternalMessageInfo - -func (m *KickAnswer) GetKicked() bool { - if m != nil { - return m.Kicked - } - return false -} - -func init() { - proto.RegisterType((*KickMsg)(nil), "protos.KickMsg") - proto.RegisterType((*KickAnswer)(nil), "protos.KickAnswer") -} - -func init() { proto.RegisterFile("kick.proto", fileDescriptor_kick_71de7c6289e550fd) } - -var fileDescriptor_kick_71de7c6289e550fd = []byte{ - // 97 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0xca, 0xce, 0x4c, 0xce, - 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x53, 0xc5, 0x4a, 0x8a, 0x5c, 0xec, 0xde, - 0x99, 0xc9, 0xd9, 0xbe, 0xc5, 0xe9, 0x42, 0x62, 0x5c, 0x6c, 0xa5, 0xc5, 0xa9, 0x45, 0x9e, 0x29, - 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x50, 0x9e, 0x92, 0x0a, 0x17, 0x17, 0x48, 0x89, 0x63, - 0x5e, 0x71, 0x79, 0x6a, 0x11, 0x48, 0x15, 0xc8, 0x98, 0x54, 0x88, 0x2a, 0x8e, 0x20, 0x28, 0x2f, - 0x09, 0x62, 0xa0, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x57, 0xec, 0x62, 0xe2, 0x65, 0x00, 0x00, - 0x00, -} diff --git a/protos/msg.pb.go b/protos/msg.pb.go deleted file mode 100644 index 4d383618..00000000 --- a/protos/msg.pb.go +++ /dev/null @@ -1,142 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: msg.proto - -package protos - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type MsgType int32 - -const ( - MsgType_MsgRequest MsgType = 0 - MsgType_MsgNotify MsgType = 1 - MsgType_MsgResponse MsgType = 2 - MsgType_MsgPush MsgType = 3 -) - -var MsgType_name = map[int32]string{ - 0: "MsgRequest", - 1: "MsgNotify", - 2: "MsgResponse", - 3: "MsgPush", -} -var MsgType_value = map[string]int32{ - "MsgRequest": 0, - "MsgNotify": 1, - "MsgResponse": 2, - "MsgPush": 3, -} - -func (x MsgType) String() string { - return proto.EnumName(MsgType_name, int32(x)) -} -func (MsgType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_msg_40ab112f05d06c13, []int{0} -} - -type Msg struct { - Id uint64 `protobuf:"varint,1,opt,name=id" json:"id,omitempty"` - Route string `protobuf:"bytes,2,opt,name=route" json:"route,omitempty"` - Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` - Reply string `protobuf:"bytes,4,opt,name=reply" json:"reply,omitempty"` - Type MsgType `protobuf:"varint,5,opt,name=type,enum=protos.MsgType" json:"type,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Msg) Reset() { *m = Msg{} } -func (m *Msg) String() string { return proto.CompactTextString(m) } -func (*Msg) ProtoMessage() {} -func (*Msg) Descriptor() ([]byte, []int) { - return fileDescriptor_msg_40ab112f05d06c13, []int{0} -} -func (m *Msg) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Msg.Unmarshal(m, b) -} -func (m *Msg) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Msg.Marshal(b, m, deterministic) -} -func (dst *Msg) XXX_Merge(src proto.Message) { - xxx_messageInfo_Msg.Merge(dst, src) -} -func (m *Msg) XXX_Size() int { - return xxx_messageInfo_Msg.Size(m) -} -func (m *Msg) XXX_DiscardUnknown() { - xxx_messageInfo_Msg.DiscardUnknown(m) -} - -var xxx_messageInfo_Msg proto.InternalMessageInfo - -func (m *Msg) GetId() uint64 { - if m != nil { - return m.Id - } - return 0 -} - -func (m *Msg) GetRoute() string { - if m != nil { - return m.Route - } - return "" -} - -func (m *Msg) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func (m *Msg) GetReply() string { - if m != nil { - return m.Reply - } - return "" -} - -func (m *Msg) GetType() MsgType { - if m != nil { - return m.Type - } - return MsgType_MsgRequest -} - -func init() { - proto.RegisterType((*Msg)(nil), "protos.Msg") - proto.RegisterEnum("protos.MsgType", MsgType_name, MsgType_value) -} - -func init() { proto.RegisterFile("msg.proto", fileDescriptor_msg_40ab112f05d06c13) } - -var fileDescriptor_msg_40ab112f05d06c13 = []byte{ - // 196 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x2c, 0x8f, 0xc1, 0x4e, 0xc6, 0x20, - 0x0c, 0xc7, 0x85, 0xf1, 0x69, 0xd6, 0xe9, 0x46, 0x1a, 0x0f, 0x1c, 0x89, 0x5e, 0x88, 0x87, 0x1d, - 0xf4, 0x1d, 0xbc, 0x61, 0x0c, 0xf1, 0x05, 0x66, 0x86, 0xb8, 0x44, 0x05, 0x57, 0x76, 0xc0, 0xa7, - 0x37, 0x1f, 0xdb, 0xa9, 0xfd, 0xf7, 0xf7, 0x6b, 0x9a, 0x42, 0xfb, 0x4d, 0x61, 0x4c, 0x6b, 0xcc, - 0x11, 0x2f, 0x6b, 0xa1, 0xbb, 0x3f, 0x68, 0x2c, 0x05, 0xec, 0x81, 0x2f, 0xb3, 0x62, 0x9a, 0x19, - 0xe1, 0xf8, 0x32, 0xe3, 0x2d, 0x9c, 0xd6, 0xb8, 0x65, 0xaf, 0xb8, 0x66, 0xa6, 0x75, 0x7b, 0x40, - 0x04, 0x31, 0x4f, 0x79, 0x52, 0x8d, 0x66, 0xe6, 0xda, 0xd5, 0xbe, 0x9a, 0x3e, 0x7d, 0x15, 0x25, - 0x0e, 0xf3, 0x1c, 0xf0, 0x1e, 0x44, 0x2e, 0xc9, 0xab, 0x93, 0x66, 0xa6, 0x7f, 0x1c, 0xf6, 0xa3, - 0x34, 0x5a, 0x0a, 0x6f, 0x25, 0x79, 0x57, 0xe1, 0xc3, 0x33, 0x5c, 0x1d, 0x03, 0xec, 0x01, 0x2c, - 0x05, 0xe7, 0x7f, 0x37, 0x4f, 0x59, 0x5e, 0xe0, 0x0d, 0xb4, 0x96, 0xc2, 0x4b, 0xcc, 0xcb, 0x47, - 0x91, 0x0c, 0x07, 0xe8, 0x2a, 0xa6, 0x14, 0x7f, 0xc8, 0x4b, 0x8e, 0x5d, 0x5d, 0x7d, 0xdd, 0xe8, - 0x53, 0x36, 0xef, 0xfb, 0x2f, 0x4f, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff, 0x8b, 0x95, 0xef, 0x13, - 0xdf, 0x00, 0x00, 0x00, -} diff --git a/protos/protodescriptor.pb.go b/protos/protodescriptor.pb.go deleted file mode 100644 index e9d8701c..00000000 --- a/protos/protodescriptor.pb.go +++ /dev/null @@ -1,195 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: protodescriptor.proto - -package protos - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -// Descriptor proto used to retrieve zipped proto descriptors remotely -type ProtoDescriptor struct { - Desc []byte `protobuf:"bytes,1,opt,name=desc,proto3" json:"desc,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ProtoDescriptor) Reset() { *m = ProtoDescriptor{} } -func (m *ProtoDescriptor) String() string { return proto.CompactTextString(m) } -func (*ProtoDescriptor) ProtoMessage() {} -func (*ProtoDescriptor) Descriptor() ([]byte, []int) { - return fileDescriptor_protodescriptor_d1dc0afa30ee5672, []int{0} -} -func (m *ProtoDescriptor) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ProtoDescriptor.Unmarshal(m, b) -} -func (m *ProtoDescriptor) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ProtoDescriptor.Marshal(b, m, deterministic) -} -func (dst *ProtoDescriptor) XXX_Merge(src proto.Message) { - xxx_messageInfo_ProtoDescriptor.Merge(dst, src) -} -func (m *ProtoDescriptor) XXX_Size() int { - return xxx_messageInfo_ProtoDescriptor.Size(m) -} -func (m *ProtoDescriptor) XXX_DiscardUnknown() { - xxx_messageInfo_ProtoDescriptor.DiscardUnknown(m) -} - -var xxx_messageInfo_ProtoDescriptor proto.InternalMessageInfo - -func (m *ProtoDescriptor) GetDesc() []byte { - if m != nil { - return m.Desc - } - return nil -} - -type ProtoName struct { - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ProtoName) Reset() { *m = ProtoName{} } -func (m *ProtoName) String() string { return proto.CompactTextString(m) } -func (*ProtoName) ProtoMessage() {} -func (*ProtoName) Descriptor() ([]byte, []int) { - return fileDescriptor_protodescriptor_d1dc0afa30ee5672, []int{1} -} -func (m *ProtoName) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ProtoName.Unmarshal(m, b) -} -func (m *ProtoName) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ProtoName.Marshal(b, m, deterministic) -} -func (dst *ProtoName) XXX_Merge(src proto.Message) { - xxx_messageInfo_ProtoName.Merge(dst, src) -} -func (m *ProtoName) XXX_Size() int { - return xxx_messageInfo_ProtoName.Size(m) -} -func (m *ProtoName) XXX_DiscardUnknown() { - xxx_messageInfo_ProtoName.DiscardUnknown(m) -} - -var xxx_messageInfo_ProtoName proto.InternalMessageInfo - -func (m *ProtoName) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -type ProtoDescriptors struct { - Desc [][]byte `protobuf:"bytes,1,rep,name=desc,proto3" json:"desc,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ProtoDescriptors) Reset() { *m = ProtoDescriptors{} } -func (m *ProtoDescriptors) String() string { return proto.CompactTextString(m) } -func (*ProtoDescriptors) ProtoMessage() {} -func (*ProtoDescriptors) Descriptor() ([]byte, []int) { - return fileDescriptor_protodescriptor_d1dc0afa30ee5672, []int{2} -} -func (m *ProtoDescriptors) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ProtoDescriptors.Unmarshal(m, b) -} -func (m *ProtoDescriptors) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ProtoDescriptors.Marshal(b, m, deterministic) -} -func (dst *ProtoDescriptors) XXX_Merge(src proto.Message) { - xxx_messageInfo_ProtoDescriptors.Merge(dst, src) -} -func (m *ProtoDescriptors) XXX_Size() int { - return xxx_messageInfo_ProtoDescriptors.Size(m) -} -func (m *ProtoDescriptors) XXX_DiscardUnknown() { - xxx_messageInfo_ProtoDescriptors.DiscardUnknown(m) -} - -var xxx_messageInfo_ProtoDescriptors proto.InternalMessageInfo - -func (m *ProtoDescriptors) GetDesc() [][]byte { - if m != nil { - return m.Desc - } - return nil -} - -type ProtoNames struct { - Name []string `protobuf:"bytes,1,rep,name=name" json:"name,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *ProtoNames) Reset() { *m = ProtoNames{} } -func (m *ProtoNames) String() string { return proto.CompactTextString(m) } -func (*ProtoNames) ProtoMessage() {} -func (*ProtoNames) Descriptor() ([]byte, []int) { - return fileDescriptor_protodescriptor_d1dc0afa30ee5672, []int{3} -} -func (m *ProtoNames) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_ProtoNames.Unmarshal(m, b) -} -func (m *ProtoNames) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_ProtoNames.Marshal(b, m, deterministic) -} -func (dst *ProtoNames) XXX_Merge(src proto.Message) { - xxx_messageInfo_ProtoNames.Merge(dst, src) -} -func (m *ProtoNames) XXX_Size() int { - return xxx_messageInfo_ProtoNames.Size(m) -} -func (m *ProtoNames) XXX_DiscardUnknown() { - xxx_messageInfo_ProtoNames.DiscardUnknown(m) -} - -var xxx_messageInfo_ProtoNames proto.InternalMessageInfo - -func (m *ProtoNames) GetName() []string { - if m != nil { - return m.Name - } - return nil -} - -func init() { - proto.RegisterType((*ProtoDescriptor)(nil), "protos.ProtoDescriptor") - proto.RegisterType((*ProtoName)(nil), "protos.ProtoName") - proto.RegisterType((*ProtoDescriptors)(nil), "protos.ProtoDescriptors") - proto.RegisterType((*ProtoNames)(nil), "protos.ProtoNames") -} - -func init() { - proto.RegisterFile("protodescriptor.proto", fileDescriptor_protodescriptor_d1dc0afa30ee5672) -} - -var fileDescriptor_protodescriptor_d1dc0afa30ee5672 = []byte{ - // 123 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2d, 0x28, 0xca, 0x2f, - 0xc9, 0x4f, 0x49, 0x2d, 0x4e, 0x2e, 0xca, 0x2c, 0x28, 0xc9, 0x2f, 0xd2, 0x03, 0xf3, 0x85, 0xd8, - 0xc0, 0x54, 0xb1, 0x92, 0x2a, 0x17, 0x7f, 0x00, 0x88, 0xe5, 0x02, 0x57, 0x20, 0x24, 0xc4, 0xc5, - 0x02, 0x52, 0x2e, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0x13, 0x04, 0x66, 0x2b, 0xc9, 0x73, 0x71, 0x82, - 0x95, 0xf9, 0x25, 0xe6, 0xa6, 0x82, 0x14, 0xe4, 0x25, 0xe6, 0xa6, 0x82, 0x15, 0x70, 0x06, 0x81, - 0xd9, 0x4a, 0x6a, 0x5c, 0x02, 0x68, 0xe6, 0x14, 0x23, 0x19, 0xc4, 0x0c, 0x37, 0x48, 0x81, 0x8b, - 0x0b, 0x6e, 0x50, 0x31, 0x92, 0x49, 0xcc, 0x30, 0x93, 0x92, 0x20, 0x2e, 0x33, 0x06, 0x04, 0x00, - 0x00, 0xff, 0xff, 0x91, 0xb4, 0x22, 0x97, 0xb9, 0x00, 0x00, 0x00, -} diff --git a/protos/push.pb.go b/protos/push.pb.go deleted file mode 100644 index 1eaa9b96..00000000 --- a/protos/push.pb.go +++ /dev/null @@ -1,90 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: push.proto - -package protos - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Push struct { - Route string `protobuf:"bytes,1,opt,name=route" json:"route,omitempty"` - Uid string `protobuf:"bytes,2,opt,name=uid" json:"uid,omitempty"` - Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Push) Reset() { *m = Push{} } -func (m *Push) String() string { return proto.CompactTextString(m) } -func (*Push) ProtoMessage() {} -func (*Push) Descriptor() ([]byte, []int) { - return fileDescriptor_push_77d28476f32095f7, []int{0} -} -func (m *Push) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Push.Unmarshal(m, b) -} -func (m *Push) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Push.Marshal(b, m, deterministic) -} -func (dst *Push) XXX_Merge(src proto.Message) { - xxx_messageInfo_Push.Merge(dst, src) -} -func (m *Push) XXX_Size() int { - return xxx_messageInfo_Push.Size(m) -} -func (m *Push) XXX_DiscardUnknown() { - xxx_messageInfo_Push.DiscardUnknown(m) -} - -var xxx_messageInfo_Push proto.InternalMessageInfo - -func (m *Push) GetRoute() string { - if m != nil { - return m.Route - } - return "" -} - -func (m *Push) GetUid() string { - if m != nil { - return m.Uid - } - return "" -} - -func (m *Push) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func init() { - proto.RegisterType((*Push)(nil), "protos.Push") -} - -func init() { proto.RegisterFile("push.proto", fileDescriptor_push_77d28476f32095f7) } - -var fileDescriptor_push_77d28476f32095f7 = []byte{ - // 100 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2a, 0x28, 0x2d, 0xce, - 0xd0, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x53, 0xc5, 0x4a, 0x4e, 0x5c, 0x2c, 0x01, - 0xa5, 0xc5, 0x19, 0x42, 0x22, 0x5c, 0xac, 0x45, 0xf9, 0xa5, 0x25, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, - 0x1a, 0x9c, 0x41, 0x10, 0x8e, 0x90, 0x00, 0x17, 0x73, 0x69, 0x66, 0x8a, 0x04, 0x13, 0x58, 0x0c, - 0xc4, 0x14, 0x12, 0xe2, 0x62, 0x49, 0x49, 0x2c, 0x49, 0x94, 0x60, 0x56, 0x60, 0xd4, 0xe0, 0x09, - 0x02, 0xb3, 0x93, 0x20, 0x66, 0x19, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x41, 0x79, 0x42, 0xe3, - 0x60, 0x00, 0x00, 0x00, -} diff --git a/protos/request.pb.go b/protos/request.pb.go deleted file mode 100644 index fe0c6c70..00000000 --- a/protos/request.pb.go +++ /dev/null @@ -1,137 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: request.proto - -package protos - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type RPCType int32 - -const ( - RPCType_Sys RPCType = 0 - RPCType_User RPCType = 1 -) - -var RPCType_name = map[int32]string{ - 0: "Sys", - 1: "User", -} -var RPCType_value = map[string]int32{ - "Sys": 0, - "User": 1, -} - -func (x RPCType) String() string { - return proto.EnumName(RPCType_name, int32(x)) -} -func (RPCType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_request_af3dbb976ee13f3b, []int{0} -} - -type Request struct { - Type RPCType `protobuf:"varint,1,opt,name=type,enum=protos.RPCType" json:"type,omitempty"` - Session *Session `protobuf:"bytes,2,opt,name=session" json:"session,omitempty"` - Msg *Msg `protobuf:"bytes,3,opt,name=msg" json:"msg,omitempty"` - FrontendID string `protobuf:"bytes,4,opt,name=frontendID" json:"frontendID,omitempty"` - Metadata []byte `protobuf:"bytes,5,opt,name=metadata,proto3" json:"metadata,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Request) Reset() { *m = Request{} } -func (m *Request) String() string { return proto.CompactTextString(m) } -func (*Request) ProtoMessage() {} -func (*Request) Descriptor() ([]byte, []int) { - return fileDescriptor_request_af3dbb976ee13f3b, []int{0} -} -func (m *Request) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Request.Unmarshal(m, b) -} -func (m *Request) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Request.Marshal(b, m, deterministic) -} -func (dst *Request) XXX_Merge(src proto.Message) { - xxx_messageInfo_Request.Merge(dst, src) -} -func (m *Request) XXX_Size() int { - return xxx_messageInfo_Request.Size(m) -} -func (m *Request) XXX_DiscardUnknown() { - xxx_messageInfo_Request.DiscardUnknown(m) -} - -var xxx_messageInfo_Request proto.InternalMessageInfo - -func (m *Request) GetType() RPCType { - if m != nil { - return m.Type - } - return RPCType_Sys -} - -func (m *Request) GetSession() *Session { - if m != nil { - return m.Session - } - return nil -} - -func (m *Request) GetMsg() *Msg { - if m != nil { - return m.Msg - } - return nil -} - -func (m *Request) GetFrontendID() string { - if m != nil { - return m.FrontendID - } - return "" -} - -func (m *Request) GetMetadata() []byte { - if m != nil { - return m.Metadata - } - return nil -} - -func init() { - proto.RegisterType((*Request)(nil), "protos.Request") - proto.RegisterEnum("protos.RPCType", RPCType_name, RPCType_value) -} - -func init() { proto.RegisterFile("request.proto", fileDescriptor_request_af3dbb976ee13f3b) } - -var fileDescriptor_request_af3dbb976ee13f3b = []byte{ - // 210 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x8f, 0xb1, 0x4e, 0x87, 0x30, - 0x10, 0x87, 0xad, 0xa0, 0xfd, 0x73, 0x88, 0x92, 0x9b, 0x1a, 0xa2, 0xa6, 0xd1, 0xa5, 0x3a, 0x30, - 0xe8, 0x23, 0xe8, 0xe2, 0x60, 0x62, 0x8a, 0x3e, 0x00, 0x86, 0x93, 0x38, 0x40, 0xb1, 0x57, 0x07, - 0xde, 0xcb, 0x07, 0x34, 0x52, 0x50, 0xa7, 0xf6, 0xbe, 0xdf, 0x77, 0x97, 0x3b, 0x28, 0x3c, 0x7d, - 0x7c, 0x12, 0x87, 0x7a, 0xf2, 0x2e, 0x38, 0x3c, 0x5c, 0x1e, 0xae, 0x0a, 0x26, 0xe6, 0x77, 0x37, - 0x46, 0x5c, 0x65, 0x03, 0xf7, 0xf1, 0x7b, 0xf1, 0x25, 0x40, 0xda, 0xd8, 0x83, 0x97, 0x90, 0x86, - 0x79, 0x22, 0x25, 0xb4, 0x30, 0xc7, 0x37, 0x27, 0xd1, 0xe0, 0xda, 0x3e, 0xdd, 0x3d, 0xcf, 0x13, - 0xd9, 0x25, 0xc4, 0x2b, 0x90, 0xeb, 0x30, 0xb5, 0xaf, 0x85, 0xc9, 0xff, 0xbc, 0x26, 0x62, 0xbb, - 0xe5, 0x78, 0x06, 0xc9, 0xc0, 0xbd, 0x4a, 0x16, 0x2d, 0xdf, 0xb4, 0x47, 0xee, 0xed, 0x0f, 0xc7, - 0x73, 0x80, 0x37, 0xef, 0xc6, 0x40, 0x63, 0xf7, 0x70, 0xaf, 0x52, 0x2d, 0x4c, 0x66, 0xff, 0x11, - 0xac, 0x60, 0x37, 0x50, 0x68, 0xbb, 0x36, 0xb4, 0xea, 0x40, 0x0b, 0x73, 0x64, 0x7f, 0xeb, 0xeb, - 0x53, 0x90, 0xeb, 0x5a, 0x28, 0x21, 0x69, 0x66, 0x2e, 0xf7, 0x70, 0x07, 0xe9, 0x0b, 0x93, 0x2f, - 0xc5, 0x6b, 0x3c, 0xfb, 0xf6, 0x3b, 0x00, 0x00, 0xff, 0xff, 0x1a, 0x3f, 0x60, 0xec, 0x0e, 0x01, - 0x00, 0x00, -} diff --git a/protos/response.pb.go b/protos/response.pb.go deleted file mode 100644 index d9e00576..00000000 --- a/protos/response.pb.go +++ /dev/null @@ -1,82 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: response.proto - -package protos - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Response struct { - Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` - Error *Error `protobuf:"bytes,2,opt,name=error" json:"error,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Response) Reset() { *m = Response{} } -func (m *Response) String() string { return proto.CompactTextString(m) } -func (*Response) ProtoMessage() {} -func (*Response) Descriptor() ([]byte, []int) { - return fileDescriptor_response_eb66de3736cab2fc, []int{0} -} -func (m *Response) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Response.Unmarshal(m, b) -} -func (m *Response) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Response.Marshal(b, m, deterministic) -} -func (dst *Response) XXX_Merge(src proto.Message) { - xxx_messageInfo_Response.Merge(dst, src) -} -func (m *Response) XXX_Size() int { - return xxx_messageInfo_Response.Size(m) -} -func (m *Response) XXX_DiscardUnknown() { - xxx_messageInfo_Response.DiscardUnknown(m) -} - -var xxx_messageInfo_Response proto.InternalMessageInfo - -func (m *Response) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func (m *Response) GetError() *Error { - if m != nil { - return m.Error - } - return nil -} - -func init() { - proto.RegisterType((*Response)(nil), "protos.Response") -} - -func init() { proto.RegisterFile("response.proto", fileDescriptor_response_eb66de3736cab2fc) } - -var fileDescriptor_response_eb66de3736cab2fc = []byte{ - // 105 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2b, 0x4a, 0x2d, 0x2e, - 0xc8, 0xcf, 0x2b, 0x4e, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x53, 0xc5, 0x52, - 0xdc, 0xa9, 0x45, 0x45, 0xf9, 0x45, 0x10, 0x41, 0x25, 0x67, 0x2e, 0x8e, 0x20, 0xa8, 0x32, 0x21, - 0x21, 0x2e, 0x96, 0x94, 0xc4, 0x92, 0x44, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x9e, 0x20, 0x30, 0x5b, - 0x48, 0x99, 0x8b, 0x15, 0xac, 0x5c, 0x82, 0x49, 0x81, 0x51, 0x83, 0xdb, 0x88, 0x17, 0xa2, 0xad, - 0x58, 0xcf, 0x15, 0x24, 0x18, 0x04, 0x91, 0x4b, 0x82, 0x98, 0x6c, 0x0c, 0x08, 0x00, 0x00, 0xff, - 0xff, 0xfc, 0x95, 0xc0, 0x6b, 0x72, 0x00, 0x00, 0x00, -} diff --git a/protos/session.pb.go b/protos/session.pb.go deleted file mode 100644 index 96935c38..00000000 --- a/protos/session.pb.go +++ /dev/null @@ -1,90 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: session.proto - -package protos - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type Session struct { - Id int64 `protobuf:"varint,1,opt,name=id" json:"id,omitempty"` - Uid string `protobuf:"bytes,2,opt,name=uid" json:"uid,omitempty"` - Data []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Session) Reset() { *m = Session{} } -func (m *Session) String() string { return proto.CompactTextString(m) } -func (*Session) ProtoMessage() {} -func (*Session) Descriptor() ([]byte, []int) { - return fileDescriptor_session_4ab38c3ef8b6fd7a, []int{0} -} -func (m *Session) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Session.Unmarshal(m, b) -} -func (m *Session) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Session.Marshal(b, m, deterministic) -} -func (dst *Session) XXX_Merge(src proto.Message) { - xxx_messageInfo_Session.Merge(dst, src) -} -func (m *Session) XXX_Size() int { - return xxx_messageInfo_Session.Size(m) -} -func (m *Session) XXX_DiscardUnknown() { - xxx_messageInfo_Session.DiscardUnknown(m) -} - -var xxx_messageInfo_Session proto.InternalMessageInfo - -func (m *Session) GetId() int64 { - if m != nil { - return m.Id - } - return 0 -} - -func (m *Session) GetUid() string { - if m != nil { - return m.Uid - } - return "" -} - -func (m *Session) GetData() []byte { - if m != nil { - return m.Data - } - return nil -} - -func init() { - proto.RegisterType((*Session)(nil), "protos.Session") -} - -func init() { proto.RegisterFile("session.proto", fileDescriptor_session_4ab38c3ef8b6fd7a) } - -var fileDescriptor_session_4ab38c3ef8b6fd7a = []byte{ - // 103 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0x2d, 0x4e, 0x2d, 0x2e, - 0xce, 0xcc, 0xcf, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x03, 0x53, 0xc5, 0x4a, 0xf6, - 0x5c, 0xec, 0xc1, 0x10, 0x09, 0x21, 0x3e, 0x2e, 0xa6, 0xcc, 0x14, 0x09, 0x46, 0x05, 0x46, 0x0d, - 0xe6, 0x20, 0xa6, 0xcc, 0x14, 0x21, 0x01, 0x2e, 0xe6, 0xd2, 0xcc, 0x14, 0x09, 0x26, 0x05, 0x46, - 0x0d, 0xce, 0x20, 0x10, 0x53, 0x48, 0x88, 0x8b, 0x25, 0x25, 0xb1, 0x24, 0x51, 0x82, 0x59, 0x81, - 0x51, 0x83, 0x27, 0x08, 0xcc, 0x4e, 0x82, 0x18, 0x64, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0x90, - 0x07, 0x5b, 0x46, 0x60, 0x00, 0x00, 0x00, -} diff --git a/protos/test/somestruct.pb.go b/protos/test/somestruct.pb.go deleted file mode 100644 index e34f39e1..00000000 --- a/protos/test/somestruct.pb.go +++ /dev/null @@ -1,81 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: somestruct.proto - -package test - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type SomeStruct struct { - A int32 `protobuf:"varint,1,opt,name=A" json:"A,omitempty"` - B string `protobuf:"bytes,2,opt,name=B" json:"B,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *SomeStruct) Reset() { *m = SomeStruct{} } -func (m *SomeStruct) String() string { return proto.CompactTextString(m) } -func (*SomeStruct) ProtoMessage() {} -func (*SomeStruct) Descriptor() ([]byte, []int) { - return fileDescriptor_somestruct_0b613b601297f11c, []int{0} -} -func (m *SomeStruct) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_SomeStruct.Unmarshal(m, b) -} -func (m *SomeStruct) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_SomeStruct.Marshal(b, m, deterministic) -} -func (dst *SomeStruct) XXX_Merge(src proto.Message) { - xxx_messageInfo_SomeStruct.Merge(dst, src) -} -func (m *SomeStruct) XXX_Size() int { - return xxx_messageInfo_SomeStruct.Size(m) -} -func (m *SomeStruct) XXX_DiscardUnknown() { - xxx_messageInfo_SomeStruct.DiscardUnknown(m) -} - -var xxx_messageInfo_SomeStruct proto.InternalMessageInfo - -func (m *SomeStruct) GetA() int32 { - if m != nil { - return m.A - } - return 0 -} - -func (m *SomeStruct) GetB() string { - if m != nil { - return m.B - } - return "" -} - -func init() { - proto.RegisterType((*SomeStruct)(nil), "test.SomeStruct") -} - -func init() { proto.RegisterFile("somestruct.proto", fileDescriptor_somestruct_0b613b601297f11c) } - -var fileDescriptor_somestruct_0b613b601297f11c = []byte{ - // 90 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x28, 0xce, 0xcf, 0x4d, - 0x2d, 0x2e, 0x29, 0x2a, 0x4d, 0x2e, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x29, 0x49, - 0x2d, 0x2e, 0x51, 0xd2, 0xe0, 0xe2, 0x0a, 0xce, 0xcf, 0x4d, 0x0d, 0x06, 0xcb, 0x08, 0xf1, 0x70, - 0x31, 0x3a, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0xb0, 0x06, 0x31, 0x3a, 0x82, 0x78, 0x4e, 0x12, 0x4c, - 0x0a, 0x8c, 0x1a, 0x9c, 0x41, 0x8c, 0x4e, 0x49, 0x6c, 0x60, 0x6d, 0xc6, 0x80, 0x00, 0x00, 0x00, - 0xff, 0xff, 0x3d, 0x9b, 0x98, 0xe0, 0x4a, 0x00, 0x00, 0x00, -} diff --git a/protos/test/testrequest.pb.go b/protos/test/testrequest.pb.go deleted file mode 100644 index 8fea27f2..00000000 --- a/protos/test/testrequest.pb.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: testrequest.proto - -package test - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type TestRequest struct { - Msg string `protobuf:"bytes,1,opt,name=msg" json:"msg,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TestRequest) Reset() { *m = TestRequest{} } -func (m *TestRequest) String() string { return proto.CompactTextString(m) } -func (*TestRequest) ProtoMessage() {} -func (*TestRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_testrequest_64ede5bd0b1b0648, []int{0} -} -func (m *TestRequest) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TestRequest.Unmarshal(m, b) -} -func (m *TestRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TestRequest.Marshal(b, m, deterministic) -} -func (dst *TestRequest) XXX_Merge(src proto.Message) { - xxx_messageInfo_TestRequest.Merge(dst, src) -} -func (m *TestRequest) XXX_Size() int { - return xxx_messageInfo_TestRequest.Size(m) -} -func (m *TestRequest) XXX_DiscardUnknown() { - xxx_messageInfo_TestRequest.DiscardUnknown(m) -} - -var xxx_messageInfo_TestRequest proto.InternalMessageInfo - -func (m *TestRequest) GetMsg() string { - if m != nil { - return m.Msg - } - return "" -} - -func init() { - proto.RegisterType((*TestRequest)(nil), "test.TestRequest") -} - -func init() { proto.RegisterFile("testrequest.proto", fileDescriptor_testrequest_64ede5bd0b1b0648) } - -var fileDescriptor_testrequest_64ede5bd0b1b0648 = []byte{ - // 79 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2c, 0x49, 0x2d, 0x2e, - 0x29, 0x4a, 0x2d, 0x2c, 0x4d, 0x2d, 0x2e, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x01, - 0x09, 0x29, 0xc9, 0x73, 0x71, 0x87, 0xa4, 0x16, 0x97, 0x04, 0x41, 0xa4, 0x84, 0x04, 0xb8, 0x98, - 0x73, 0x8b, 0xd3, 0x25, 0x18, 0x15, 0x18, 0x35, 0x38, 0x83, 0x40, 0xcc, 0x24, 0x36, 0xb0, 0x6a, - 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x8e, 0xca, 0x49, 0xd7, 0x42, 0x00, 0x00, 0x00, -} diff --git a/protos/test/testresponse.pb.go b/protos/test/testresponse.pb.go deleted file mode 100644 index eb1c7574..00000000 --- a/protos/test/testresponse.pb.go +++ /dev/null @@ -1,81 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: testresponse.proto - -package test - -import proto "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package - -type TestResponse struct { - Code int32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"` - Msg string `protobuf:"bytes,2,opt,name=msg" json:"msg,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *TestResponse) Reset() { *m = TestResponse{} } -func (m *TestResponse) String() string { return proto.CompactTextString(m) } -func (*TestResponse) ProtoMessage() {} -func (*TestResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_testresponse_54303195d9d8e908, []int{0} -} -func (m *TestResponse) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_TestResponse.Unmarshal(m, b) -} -func (m *TestResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_TestResponse.Marshal(b, m, deterministic) -} -func (dst *TestResponse) XXX_Merge(src proto.Message) { - xxx_messageInfo_TestResponse.Merge(dst, src) -} -func (m *TestResponse) XXX_Size() int { - return xxx_messageInfo_TestResponse.Size(m) -} -func (m *TestResponse) XXX_DiscardUnknown() { - xxx_messageInfo_TestResponse.DiscardUnknown(m) -} - -var xxx_messageInfo_TestResponse proto.InternalMessageInfo - -func (m *TestResponse) GetCode() int32 { - if m != nil { - return m.Code - } - return 0 -} - -func (m *TestResponse) GetMsg() string { - if m != nil { - return m.Msg - } - return "" -} - -func init() { - proto.RegisterType((*TestResponse)(nil), "test.TestResponse") -} - -func init() { proto.RegisterFile("testresponse.proto", fileDescriptor_testresponse_54303195d9d8e908) } - -var fileDescriptor_testresponse_54303195d9d8e908 = []byte{ - // 96 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2a, 0x49, 0x2d, 0x2e, - 0x29, 0x4a, 0x2d, 0x2e, 0xc8, 0xcf, 0x2b, 0x4e, 0xd5, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, - 0x01, 0x89, 0x29, 0x99, 0x70, 0xf1, 0x84, 0xa4, 0x16, 0x97, 0x04, 0x41, 0xe5, 0x84, 0x84, 0xb8, - 0x58, 0x92, 0xf3, 0x53, 0x52, 0x25, 0x18, 0x15, 0x18, 0x35, 0x58, 0x83, 0xc0, 0x6c, 0x21, 0x01, - 0x2e, 0xe6, 0xdc, 0xe2, 0x74, 0x09, 0x26, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x10, 0x33, 0x89, 0x0d, - 0x6c, 0x84, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x6a, 0x18, 0xc0, 0x42, 0x58, 0x00, 0x00, 0x00, -} diff --git a/repl/commands.go b/repl/commands.go new file mode 100644 index 00000000..46fa8a83 --- /dev/null +++ b/repl/commands.go @@ -0,0 +1,170 @@ +// Copyright (c) Wildlife Studios. All Rights Reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package repl + +import ( + "encoding/json" + "errors" + "github.com/topfreegames/pitaya/v3/pkg/client" + "strings" + + "github.com/sirupsen/logrus" + "github.com/topfreegames/pitaya/v3/pkg/logger" +) + +func connect(addr string, onMessageCallback func([]byte)) (err error) { + if pClient != nil && pClient.ConnectedStatus() { + return errors.New("already connected") + } + + switch { + case docsString != "": + err = protoClient(addr) + default: + logger.Log.Info("Using json client") + pClient = client.New(logrus.InfoLevel) + } + pClient.SetClientHandshakeData(handshake) + + if err != nil { + return err + } + + if err = tryConnect(addr); err != nil { + logger.Log.Error("Failed to connect!") + return err + } + + logger.Log.Info("connected!") + disconnectedCh = make(chan bool, 1) + go readServerMessages(onMessageCallback) + + return nil +} + +func setHandshake(args []string) error { + + // Try first unserializing arguments as a json. + err := json.Unmarshal([]byte(strings.Join(args[:], "")), &handshake) + if err == nil { + return nil + } + + if len(args) == 2 { + if args[0] != "version" && args[0] != "platform" && args[0] != "buildNumber" { + return errors.New("invalid argument to sethandshake, expected version, platform or buildNumber") + } + switch arg := args[0]; arg { + case "version": + handshake.Sys.Version = args[1] + case "platform": + handshake.Sys.Platform = args[1] + case "buildNumber": + handshake.Sys.BuildNumber = args[1] + } + return nil + } + + return errors.New("invalid number of arguments, expected 1 argument or 2 arguments ") +} + +func push(args []string) error { + if pClient != nil { + return errors.New("use this command before connect") + } + + if len(args) != 2 { + return errors.New(`push should be in the format: push {route} {type}`) + } + + route := args[0] + pushType := args[1] + + if docsString == "" { + logger.Log.Warn("Only for probuffer servers") + return nil + } + + pushInfo[route] = pushType + + return nil +} + +func request(args []string) error { + if pClient == nil { + return errors.New("not connected") + } + + if !pClient.ConnectedStatus() { + return errors.New("not connected") + } + + if len(args) < 1 { + return errors.New(`request should be in the format: request {route} [data]`) + } + + route := args[0] + + var data []byte + if len(args) > 1 { + data = []byte(strings.Join(args[1:], "")) + } + + _, err := pClient.SendRequest(route, data) + if err != nil { + return err + } + + return nil +} + +func notify(args []string) error { + if pClient == nil { + return errors.New("not connected") + } + + if !pClient.ConnectedStatus() { + return errors.New("not connected") + } + + if len(args) < 1 { + return errors.New(`notify should be in the format: notify {route} [data]`) + } + + route := args[0] + var data []byte + if len(args) > 1 { + data = []byte(strings.Join(args[1:], "")) + } + + if err := pClient.SendNotify(route, data); err != nil { + return err + } + + return nil +} + +func disconnect() { + if pClient.ConnectedStatus() { + disconnectedCh <- true + pClient.Disconnect() + } +} diff --git a/repl/file.go b/repl/file.go new file mode 100644 index 00000000..8ca8abec --- /dev/null +++ b/repl/file.go @@ -0,0 +1,96 @@ +// Copyright (c) Wildlife Studios. All Rights Reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package repl + +import ( + "bufio" + "errors" + "log" + "os" + "strings" + + "github.com/topfreegames/pitaya/v3/pkg/logger" +) + +func executeFromFile(fileName string) { + var err error + defer func() { + if err != nil { + logger.Log.Errorf("error: %s", err.Error()) + } + }() + + var file *os.File + file, err = os.Open(fileName) + if err != nil { + return + } + + scanner := bufio.NewScanner(file) + for scanner.Scan() { + command := scanner.Text() + err = executeCommand(command) + if err != nil { + return + } + } + + err = scanner.Err() + if err != nil { + return + } +} + +func executeCommand(command string) error { + parts := strings.Split(command, " ") + + switch parts[0] { + case "connect": + return connect(parts[1], func(data []byte) { + log.Printf("sv-> %s\n", string(data)) + wait.Done() + }) + + case "sethandshake": + return setHandshake(parts[1:]) + + case "request": + wait.Add(1) + if err := request(parts[1:]); err != nil { + return err + } + wait.Wait() + return nil + + case "notify": + return notify(parts[1:]) + + case "push": + return push(parts[1:]) + + case "disconnect": + disconnect() + return nil + + default: + return errors.New("command not found") + } +} diff --git a/repl/helpers.go b/repl/helpers.go new file mode 100644 index 00000000..7925c046 --- /dev/null +++ b/repl/helpers.go @@ -0,0 +1,102 @@ +// Copyright (c) Wildlife Studios. All Rights Reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package repl + +import ( + "crypto/tls" + "encoding/json" + "fmt" + "github.com/topfreegames/pitaya/v3/pkg/client" + "log" + "os" + + "github.com/mitchellh/go-homedir" + "github.com/sirupsen/logrus" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "gopkg.in/abiosoft/ishell.v2" +) + +func protoClient(addr string) error { + log.Println("Using protobuf client") + protoclient := client.NewProto(docsString, logrus.InfoLevel) + pClient = protoclient + + for k, v := range pushInfo { + protoclient.AddPushResponse(k, v) + } + + if err := protoclient.LoadServerInfo(addr); err != nil { + logger.Log.Errorf("Failed to load server info: %s", err.Error()) + return err + } + + return nil +} + +func tryConnect(addr string) error { + if err := pClient.ConnectToWS(addr, "", &tls.Config{ + InsecureSkipVerify: true, + }); err != nil { + if err := pClient.ConnectToWS(addr, ""); err != nil { + if err := pClient.ConnectTo(addr, &tls.Config{ + InsecureSkipVerify: true, + }); err != nil { + if err := pClient.ConnectTo(addr); err != nil { + return err + } + } + } + } + return nil +} + +func readServerMessages(callback func(data []byte)) { + channel := pClient.MsgChannel() + for { + select { + case <-disconnectedCh: + close(disconnectedCh) + return + case m := <-channel: + callback(parseData(m.Data)) + } + } +} + +func configure(c *ishell.Shell) { + historyPath := os.Getenv("PITAYACLI_HISTORY_PATH") + if historyPath == "" { + home, _ := homedir.Dir() + historyPath = fmt.Sprintf("%s/.pitayacli_history", home) + } + + c.SetHistoryPath(historyPath) +} + +func parseData(data []byte) []byte { + if prettyJSON { + var m interface{} + _ = json.Unmarshal(data, &m) + data, _ = json.MarshalIndent(m, "", "\t") + } + + return data +} diff --git a/repl/repl.go b/repl/repl.go new file mode 100644 index 00000000..ce76641d --- /dev/null +++ b/repl/repl.go @@ -0,0 +1,58 @@ +/* +Copyright © 2021 Wildlife Studios + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package repl + +import ( + "github.com/topfreegames/pitaya/v3/pkg/client" + "sync" + + "github.com/topfreegames/pitaya/v3/pkg/session" +) + +var ( + pClient client.PitayaClient + disconnectedCh chan bool + docsString string + fileName string + pushInfo map[string]string + wait sync.WaitGroup + prettyJSON bool + handshake *session.HandshakeData +) + +func Start(docs, filename string, prettyJSON bool) { + docsString = docs + fileName = filename + handshake = &session.HandshakeData{ + Sys: session.HandshakeClientData{ + Platform: "repl", + LibVersion: "1.3.1", + BuildNumber: "20", + Version: "1.0.0", + }, + User: map[string]interface{}{ + "client": "repl", + }, + } + + switch { + case fileName != "": + executeFromFile(fileName) + default: + repl() + } +} diff --git a/repl/shell.go b/repl/shell.go new file mode 100644 index 00000000..9c02d3e8 --- /dev/null +++ b/repl/shell.go @@ -0,0 +1,127 @@ +// Copyright (c) Wildlife Studios. All Rights Reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +package repl + +import ( + "gopkg.in/abiosoft/ishell.v2" +) + +func repl() { + shell := ishell.New() + configure(shell) + + shell.Println("Pitaya REPL Client") + + registerConnect(shell) + registerDisconnect(shell) + registerRequest(shell) + registerNotify(shell) + registerPush(shell) + registerSetHandshake(shell) + + pushInfo = make(map[string]string) + + shell.Run() +} + +func registerConnect(shell *ishell.Shell) { + shell.AddCmd(&ishell.Cmd{ + Name: "connect", + Help: "connects to pitaya", + Func: func(c *ishell.Context) { + var addr string + if len(c.Args) == 0 { + c.Print("address: ") + addr = c.ReadLine() + } else { + addr = c.Args[0] + } + + if err := connect(addr, func(data []byte) { + c.Printf("sv->%s\n", string(data)) + }); err != nil { + c.Err(err) + } + }, + }) +} + +func registerPush(shell *ishell.Shell) { + shell.AddCmd(&ishell.Cmd{ + Name: "push", + Help: "insert information of push return", + Func: func(c *ishell.Context) { + err := push(c.RawArgs[1:]) + if err != nil { + c.Err(err) + } + }, + }) +} + +func registerRequest(shell *ishell.Shell) { + shell.AddCmd(&ishell.Cmd{ + Name: "request", + Help: "makes a request to pitaya server", + Func: func(c *ishell.Context) { + err := request(c.RawArgs[1:]) + if err != nil { + c.Err(err) + } + }, + }) +} + +func registerNotify(shell *ishell.Shell) { + shell.AddCmd(&ishell.Cmd{ + Name: "notify", + Help: "makes a notify to pitaya server", + Func: func(c *ishell.Context) { + err := notify(c.RawArgs[1:]) + if err != nil { + c.Err(err) + } + }, + }) +} + +func registerDisconnect(shell *ishell.Shell) { + shell.AddCmd(&ishell.Cmd{ + Name: "disconnect", + Help: "disconnects from pitaya server", + Func: func(c *ishell.Context) { + disconnect() + }, + }) +} + +func registerSetHandshake(shell *ishell.Shell) { + shell.AddCmd(&ishell.Cmd{ + Name: "sethandshake", + Help: "sets a handshake parameter", + Func: func(c *ishell.Context) { + err := setHandshake(c.RawArgs[1:]) + if err != nil { + c.Err(err) + } + }, + }) +} diff --git a/session/test/static_test.go b/session/test/static_test.go deleted file mode 100644 index 8f3f6111..00000000 --- a/session/test/static_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package test - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/google/uuid" - "github.com/stretchr/testify/require" - "github.com/topfreegames/pitaya/v2/session" - "github.com/topfreegames/pitaya/v2/session/mocks" -) - -func TestStaticGetSessionByUID(t *testing.T) { - createSessionMock := func(ctrl *gomock.Controller) session.Session { - return mocks.NewMockSession(ctrl) - } - createNilSession := func(ctrl *gomock.Controller) session.Session { - return mocks.NewMockSession(ctrl) - } - - tables := []struct { - name string - uid string - factory func(ctrl *gomock.Controller) session.Session - }{ - {"Success", uuid.New().String(), createSessionMock}, - {"Error", uuid.New().String(), createNilSession}, - } - - for _, row := range tables { - t.Run(row.name, func(t *testing.T) { - ctrl := gomock.NewController(t) - - expectedSession := row.factory(ctrl) - - sessionPool := mocks.NewMockSessionPool(ctrl) - sessionPool.EXPECT().GetSessionByUID(row.uid).Return(expectedSession) - - session.DefaultSessionPool = sessionPool - session := session.GetSessionByUID(row.uid) - require.Equal(t, expectedSession, session) - }) - } -} - -func TestStaticGetSessionByID(t *testing.T) { - createSessionMock := func(ctrl *gomock.Controller) session.Session { - return mocks.NewMockSession(ctrl) - } - createNilSession := func(ctrl *gomock.Controller) session.Session { - return mocks.NewMockSession(ctrl) - } - - tables := []struct { - name string - id int64 - factory func(ctrl *gomock.Controller) session.Session - }{ - {"Success", 3, createSessionMock}, - {"Error", 3, createNilSession}, - } - - for _, row := range tables { - t.Run(row.name, func(t *testing.T) { - ctrl := gomock.NewController(t) - - expectedSession := row.factory(ctrl) - - sessionPool := mocks.NewMockSessionPool(ctrl) - sessionPool.EXPECT().GetSessionByID(row.id).Return(expectedSession) - - session.DefaultSessionPool = sessionPool - session := session.GetSessionByID(row.id) - require.Equal(t, expectedSession, session) - }) - } -} - -func TestStaticOnSessionBind(t *testing.T) { - ctrl := gomock.NewController(t) - - sessionPool := mocks.NewMockSessionPool(ctrl) - sessionPool.EXPECT().OnSessionBind(nil) - - session.DefaultSessionPool = sessionPool - session.OnSessionBind(nil) -} - -func TestStaticOnAfterSessionBind(t *testing.T) { - ctrl := gomock.NewController(t) - - sessionPool := mocks.NewMockSessionPool(ctrl) - sessionPool.EXPECT().OnAfterSessionBind(nil) - - session.DefaultSessionPool = sessionPool - session.OnAfterSessionBind(nil) -} - -func TestStaticOnSessionClose(t *testing.T) { - ctrl := gomock.NewController(t) - - sessionPool := mocks.NewMockSessionPool(ctrl) - sessionPool.EXPECT().OnSessionClose(nil) - - session.DefaultSessionPool = sessionPool - session.OnSessionClose(nil) -} - -func TestStaticCloseAll(t *testing.T) { - ctrl := gomock.NewController(t) - - sessionPool := mocks.NewMockSessionPool(ctrl) - sessionPool.EXPECT().CloseAll() - - session.DefaultSessionPool = sessionPool - session.CloseAll() -} diff --git a/sidecar/globals.go b/sidecar/globals.go new file mode 100644 index 00000000..103b3330 --- /dev/null +++ b/sidecar/globals.go @@ -0,0 +1,29 @@ +package sidecar + +import ( + "context" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "google.golang.org/protobuf/types/known/emptypb" + "sync" +) + +// Call struct represents an incoming RPC call from other servers +type Call struct { + ctx context.Context + req *protos.Request + done chan (bool) + res *protos.Response + err *protos.Error + reqId uint64 +} + +var ( + stopChan = make(chan bool) + callChan = make(chan *Call) + sdChan = make(chan *protos.SDEvent) + shouldRun = true + redId uint64 + reqMutex sync.RWMutex + reqMap = make(map[uint64]*Call) + empty = &emptypb.Empty{} +) diff --git a/sidecar/server.go b/sidecar/server.go new file mode 100644 index 00000000..5538efc1 --- /dev/null +++ b/sidecar/server.go @@ -0,0 +1,276 @@ +package sidecar + +import ( + "context" + pitaya "github.com/topfreegames/pitaya/v3/pkg" + "github.com/topfreegames/pitaya/v3/pkg/config" + "github.com/topfreegames/pitaya/v3/pkg/errors" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/logger/logrus" + "github.com/topfreegames/pitaya/v3/pkg/protos" + "github.com/topfreegames/pitaya/v3/pkg/tracing" + "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/emptypb" + "net" + "os" + "os/signal" + "syscall" +) + +// Server is the implementation of the GRPC server used to communicate +// with the sidecar client +type Server struct { + pitaya pitaya.Pitaya + sidecar *Sidecar + config config.BuilderConfig + protos.UnimplementedPitayaServer +} + +func NewServer(sidecar *Sidecar, config config.BuilderConfig) *Server{ + return &Server{ + sidecar: sidecar, + config: config, + } +} + +func NewServerWithPitaya(pitaya pitaya.Pitaya) *Server{ + return &Server{ + pitaya: pitaya, + } +} + +// Start starts the sidecar server, it instantiates the GRPC server and +// listens for incoming client connections. This is the very first method that +// is called when the sidecar is starting. +func (s *Server) Start(bindAddr, bindProto string) { + if bindProto != "unix" && bindProto != "tcp" { + logger.Log.Fatal("only supported schemes are unix and tcp, review your bindaddr config") + } + var err error + listener, err := net.Listen(bindProto, bindAddr) + checkError(err) + + defer listener.Close() + + var opts []grpc.ServerOption + grpcServer := grpc.NewServer(opts...) + protos.RegisterSidecarServer(grpcServer, s) + go func() { + err = grpcServer.Serve(listener) + if err != nil { + logger.Log.Errorf("error serving GRPC: %s", err) + select { + case <-stopChan: + break + default: + close(stopChan) + } + } + }() + + // TODO: what to do if received sigint/term without receiving stop request from client? + logger.Log.Infof("sidecar listening at %s", listener.Addr()) + + sg := make(chan os.Signal) + signal.Notify(sg, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGTERM) + + // TODO make jaeger optional and configure with configs + configureJaeger(true) + + // stop server + select { + case <-sg: + logger.Log.Warn("got signal: ", sg, ", shutting down...") + close(stopChan) + break + case <-stopChan: + logger.Log.Warn("the app will shutdown in a few seconds") + } + + s.pitaya.Shutdown().Wait() +} + + +// GetServer is called by the sidecar client to get the information from +// a pitaya server by passing its ID +func (s Server) GetServer(ctx context.Context, in *protos.Server) (*protos.Server, error) { + server, err := pitaya.GetServerByID(in.Id) + if err != nil { + return nil, err + } + res := &protos.Server{ + Id: server.ID, + Frontend: server.Frontend, + Type: server.Type, + Metadata: server.Metadata, + Hostname: server.Hostname, + } + return res, nil +} + +func (s *Server) Heartbeat(ctx context.Context, in *emptypb.Empty) (*emptypb.Empty, error) { + logger.Log.Debug("Received heartbeat from the sidecar client") + return empty, nil +} + +// ListenSD keeps a stream open between the sidecar client and server, it sends +// service discovery events to the sidecar client, such as add or removal of +// servers in the cluster +func (s *Server) ListenSD(empty *emptypb.Empty, stream protos.Sidecar_ListenSDServer) error { + for shouldRun { + select { + case evt := <-sdChan: + err := stream.Send(evt) + if err != nil { + logger.Log.Warnf("error sending sd event to sidecar client: %s", err.Error) + } + case <-stopChan: + shouldRun = false + } + } + logger.Log.Info("exiting sidecar ListenSD routine because stopChan was closed") + return nil +} + +// ListenRPC keeps a bidirectional stream open between the sidecar client and +// server, it sends incoming RPC from other pitaya servers to the client and +// also listens for incoming answers from the client. This method is the most +// important one here and is where is defined our async model. +func (s *Server) ListenRPC(stream protos.Sidecar_ListenRPCServer) error { + go func() { + for { + res, err := stream.Recv() + if err != nil { + select { + case <-stopChan: + return + default: + close(stopChan) + return + } + } + // TODO fix context to fix tracing + s.finishRPC(context.Background(), res) + } + }() + for shouldRun { + select { + case call := <- callChan: + err := stream.Send(&protos.SidecarRequest{ReqId: call.reqId, Req: call.req}) + if err != nil { + call.err = &protos.Error{Msg: err.Error(), Code: errors.ErrBadRequestCode} + close(call.done) + } + case <-stopChan: + shouldRun = false + } + } + logger.Log.Info("exiting sidecar ListenRPC routine because stopChan was closed") + return nil +} + +// finishRPC is called when the sidecar client returns the answer to an RPC +// call, after this method happens, the Call method above returns +func (s *Server) finishRPC(ctx context.Context, res *protos.RPCResponse) { + reqMutex.RLock() + defer reqMutex.RUnlock() + call, ok := reqMap[res.ReqId] + if ok { + call.res = res.Res + call.err = res.Err + close(call.done) + } +} + + +// SendRPC is called by the sidecar client when it wants to send RPC requests to +// other pitaya servers +func (s *Server) SendRPC(ctx context.Context, in *protos.RequestTo) (*protos.Response, error) { + pCtx := getCtxWithParentSpan(ctx, in.Msg.Route) + ret, err := s.pitaya.RawRPC(pCtx, in.ServerID, in.Msg.Route, in.Msg.Data) + defer tracing.FinishSpan(pCtx, err) + return ret, err +} + +// SendPush is called by the sidecar client when it wants to send a push to an +// user through a frontend server +func (s *Server) SendPush(ctx context.Context, in *protos.PushRequest) (*protos.PushResponse, error) { + push := in.GetPush() + failedUids, err := pitaya.SendPushToUsers(push.Route, push.GetData(), []string{push.Uid}, in.FrontendType) + res := &protos.PushResponse{ + FailedUids: failedUids, + } + if err != nil { + res.HasFailed = true + } else { + res.HasFailed = false + } + return res, nil // can't send the error here because if we do, it will throw an exception in csharp side +} + +// SendKick is called by the sidecar client when it wants to send a kick to an +// user through a frontend server +func (s *Server) SendKick(ctx context.Context, in *protos.KickRequest) (*protos.PushResponse, error) { + failedUids, err := pitaya.SendKickToUsers([]string{in.GetKick().GetUserId()}, in.FrontendType) + res := &protos.PushResponse{ + FailedUids: failedUids, + } + if err != nil { + res.HasFailed = true + } else { + res.HasFailed = false + } + return res, nil // can't send the error here because if we do, it will throw an exception in csharp side +} + +// StartPitaya instantiates a pitaya server and starts it. It must be called +// during the initialization of the sidecar client, all other methods will only +// work when this one was already called +func (s *Server) StartPitaya(ctx context.Context, req *protos.StartPitayaRequest) (*protos.Error, error) { + if s.pitaya != nil { + logger.Log.Info("Pitaya already initialized") + return &protos.Error{}, nil + } + + logger.Log.Info("Pitaya sasas initialized") + builder := pitaya.NewDefaultBuilder( + false, + req.Config.Type, + pitaya.Cluster, + req.Config.Metadata, + s.config, + ) + + RPCServer := builder.RPCServer + builder.ServiceDiscovery.AddListener(s.sidecar) + + s.pitaya = builder.Build() + + // register the sidecar as the pitaya server so that calls will be delivered + // here and we can forward to the remote process + RPCServer.SetPitayaServer(s.sidecar) + + // Start our own logger + log := logrus.New() + + s.pitaya.SetDebug(req.DebugLog) + + pitaya.SetLogger(log.WithField("source", "sidecar")) + + go s.pitaya.Start() + + return &protos.Error{}, nil +} + +// StopPitaya stops the instantiated pitaya server and must always be called +// when the client is dying so that we can correctly gracefully shutdown pitaya +func (s *Server) StopPitaya(ctx context.Context, req *emptypb.Empty) (*protos.Error, error) { + logger.Log.Info("received stop request, will stop pitaya server") + select { + case <-stopChan: + break + default: + close(stopChan) + } + return &protos.Error{}, nil +} \ No newline at end of file diff --git a/sidecar/sidecar.go b/sidecar/sidecar.go new file mode 100644 index 00000000..bf24abb2 --- /dev/null +++ b/sidecar/sidecar.go @@ -0,0 +1,112 @@ +package sidecar + +import ( + "context" + "github.com/topfreegames/pitaya/v3/pkg/cluster" + "github.com/topfreegames/pitaya/v3/pkg/constants" + "time" + + "sync/atomic" + + "github.com/topfreegames/pitaya/v3/pkg/protos" +) + +// TODO: implement jaeger into this, test everything, if connection dies this +// will go to hell, reconnection doesnt work, what can we do? Bench results: +// 40k req/sec bidirectional stream, around 13k req/sec (RPC) + +// TODO investigate why I will get drops in send rate every now and then during +// the benchmark test. I imagine maybe it's due to garbage collection? + +// TODO I can utilize reutilizable objects, such as with a poll and reduce +// allocations here + +// Sidecar main struct to keep state +type Sidecar struct { + callTimeout time.Duration +} + +func NewSidecar(callTimeout time.Duration) *Sidecar { + return &Sidecar{ + callTimeout: callTimeout, + } +} + +// AddServer is called by the ServiceDiscovery when a new pitaya server is +// added. We have it here so that we stream add and removed servers to sidecar +// client. +func (s *Sidecar) AddServer(server *cluster.Server) { + sdChan <- &protos.SDEvent{ + Server: &protos.Server{ + Id: server.ID, + Frontend: server.Frontend, + Type: server.Type, + Metadata: server.Metadata, + Hostname: server.Hostname, + }, + Event: protos.SDEvent_ADD, + } +} + +// RemoveServer is called by the ServiceDiscovery when a pitaya server is +// removed from the cluster. We have it here so that we stream add and removed +// servers to sidecar client. +func (s *Sidecar) RemoveServer(server *cluster.Server) { + sdChan <- &protos.SDEvent{ + Server: &protos.Server{ + Id: server.ID, + Frontend: server.Frontend, + Type: server.Type, + Metadata: server.Metadata, + Hostname: server.Hostname, + }, + Event: protos.SDEvent_REMOVE, + } +} + +// Call receives an RPC request from other pitaya servers and forward it to the +// sidecar client so that it processes them, afterwards it gets the client +// response and send it back to the callee +func (s *Sidecar) Call(ctx context.Context, req *protos.Request) (*protos.Response, error) { + call := &Call{ + ctx: ctx, + req: req, + done: make(chan (bool), 1), + reqId: atomic.AddUint64(&redId, 1), + } + + reqMutex.Lock() + reqMap[call.reqId] = call + reqMutex.Unlock() + + callChan <- call + + defer func() { + reqMutex.Lock() + delete(reqMap, call.reqId) + reqMutex.Unlock() + }() + + select { + case <-call.done: + return call.res, nil + case <-time.After(s.callTimeout): + close(call.done) + return &protos.Response{}, constants.ErrSidecarCallTimeout + } +} + +// SessionBindRemote is meant to frontend servers so its not implemented here +func (s *Sidecar) SessionBindRemote(ctx context.Context, msg *protos.BindMsg) (*protos.Response, error) { + return nil, constants.ErrNotImplemented +} + +// PushToUser is meant to frontend servers so its not implemented here +func (s *Sidecar) PushToUser(ctx context.Context, push *protos.Push) (*protos.Response, error) { + return nil, constants.ErrNotImplemented +} + +// KickUser is meant to frontend servers so its not implemented here +func (s *Sidecar) KickUser(ctx context.Context, kick *protos.KickMsg) (*protos.KickAnswer, error) { + return nil, constants.ErrNotImplemented +} \ No newline at end of file diff --git a/sidecar/utils.go b/sidecar/utils.go new file mode 100644 index 00000000..760206ad --- /dev/null +++ b/sidecar/utils.go @@ -0,0 +1,57 @@ +package sidecar + +import ( + "context" + "github.com/opentracing/opentracing-go" + "github.com/topfreegames/pitaya/v3/pkg/logger" + "github.com/topfreegames/pitaya/v3/pkg/tracing" + jaegercfg "github.com/uber/jaeger-client-go/config" + "google.golang.org/grpc/metadata" +) + +func checkError(err error) { + if err != nil { + logger.Log.Fatalf("failed to start sidecar: %s", err) + } +} + +// TODO need to replace pitayas own jaeger config with something that actually makes sense +func configureJaeger(debug bool) { + cfg, err := jaegercfg.FromEnv() + if debug { + cfg.ServiceName = "pitaya-sidecar" + cfg.Sampler.Type = "const" + cfg.Sampler.Param = 1 + } + if cfg.ServiceName == "" { + logger.Log.Error("Could not init jaeger tracer without ServiceName, either set environment JAEGER_SERVICE_NAME or cfg.ServiceName = \"my-api\"") + return + } + if err != nil { + logger.Log.Error("Could not parse Jaeger env vars: %s", err.Error()) + return + } + tracer, _, err := cfg.NewTracer() + if err != nil { + logger.Log.Error("Could not initialize jaeger tracer: %s", err.Error()) + return + } + opentracing.SetGlobalTracer(tracer) + logger.Log.Infof("Tracer configured for %s", cfg.Reporter.LocalAgentHostPort) +} + + +func getCtxWithParentSpan(ctx context.Context, op string) context.Context { + md, ok := metadata.FromIncomingContext(ctx) + if ok { + carrier := opentracing.HTTPHeadersCarrier(md) + spanContext, err := opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders, carrier) + if err != nil { + logger.Log.Debugf("tracing: could not extract span from context!") + } else { + return tracing.StartSpan(ctx, op, opentracing.Tags{}, spanContext) + } + } + return ctx +} +