From 15f1945b77e0d6a56ee2cdd628fda9b7e93a9a45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20S=C3=B8rlie=20Glomsaas?= Date: Thu, 14 Apr 2022 11:04:25 -0400 Subject: [PATCH 1/9] refactor: Rewrite protoc-gen-frisbee using the template/text package --- protoc-gen-frisbee/internal/utils/utils.go | 25 ++ protoc-gen-frisbee/pkg/generator/client.go | 163 ------- protoc-gen-frisbee/pkg/generator/defaults.go | 27 +- protoc-gen-frisbee/pkg/generator/enums.go | 40 -- protoc-gen-frisbee/pkg/generator/generator.go | 60 +-- protoc-gen-frisbee/pkg/generator/headers.go | 26 -- protoc-gen-frisbee/pkg/generator/imports.go | 14 - .../pkg/generator/interfaces.go | 53 --- protoc-gen-frisbee/pkg/generator/server.go | 67 +-- protoc-gen-frisbee/pkg/generator/structs.go | 407 +++--------------- protoc-gen-frisbee/templates/base.go.txt | 17 + protoc-gen-frisbee/templates/client.go.txt | 126 ++++++ protoc-gen-frisbee/templates/decode.go.txt | 94 ++++ protoc-gen-frisbee/templates/decodeMap.go.txt | 51 +++ protoc-gen-frisbee/templates/encode.go.txt | 41 ++ protoc-gen-frisbee/templates/encodeMap.go.txt | 33 ++ protoc-gen-frisbee/templates/enums.go.txt | 19 + protoc-gen-frisbee/templates/headers.go.txt | 6 + protoc-gen-frisbee/templates/imports.go.txt | 7 + .../templates/interfaces.go.txt | 16 + protoc-gen-frisbee/templates/messages.go.txt | 10 + protoc-gen-frisbee/templates/server.go.txt | 57 +++ protoc-gen-frisbee/templates/structs.go.txt | 57 +++ 23 files changed, 649 insertions(+), 767 deletions(-) delete mode 100644 protoc-gen-frisbee/pkg/generator/client.go delete mode 100644 protoc-gen-frisbee/pkg/generator/enums.go delete mode 100644 protoc-gen-frisbee/pkg/generator/interfaces.go create mode 100644 protoc-gen-frisbee/templates/base.go.txt create mode 100644 protoc-gen-frisbee/templates/client.go.txt create mode 100644 protoc-gen-frisbee/templates/decode.go.txt create mode 100644 protoc-gen-frisbee/templates/decodeMap.go.txt create mode 100644 protoc-gen-frisbee/templates/encode.go.txt create mode 100644 protoc-gen-frisbee/templates/encodeMap.go.txt create mode 100644 protoc-gen-frisbee/templates/enums.go.txt create mode 100644 protoc-gen-frisbee/templates/headers.go.txt create mode 100644 protoc-gen-frisbee/templates/imports.go.txt create mode 100644 protoc-gen-frisbee/templates/interfaces.go.txt create mode 100644 protoc-gen-frisbee/templates/messages.go.txt create mode 100644 protoc-gen-frisbee/templates/server.go.txt create mode 100644 protoc-gen-frisbee/templates/structs.go.txt diff --git a/protoc-gen-frisbee/internal/utils/utils.go b/protoc-gen-frisbee/internal/utils/utils.go index 9d4426a..f8f1f9c 100644 --- a/protoc-gen-frisbee/internal/utils/utils.go +++ b/protoc-gen-frisbee/internal/utils/utils.go @@ -17,6 +17,7 @@ package utils import ( + "google.golang.org/protobuf/reflect/protoreflect" "strings" "unicode" "unicode/utf8" @@ -70,6 +71,14 @@ func CamelCase(s string) string { return string(t) } +func CamelCaseFN(name protoreflect.FullName) string { + return CamelCase(string(name)) +} + +func CamelCaseN(name protoreflect.Name) string { + return CamelCase(string(name)) +} + func AppendString(inputs ...string) string { builder := new(strings.Builder) for _, s := range inputs { @@ -86,3 +95,19 @@ func FirstLowerCase(s string) string { r, n := utf8.DecodeRuneInString(s) return string(unicode.ToLower(r)) + s[n:] } + +func FirstLowerCaseN(name protoreflect.Name) string { + return FirstLowerCase(string(name)) +} + +func MakeIterable(len int) []struct{} { + return make([]struct{}, len) +} + +func Counter(initial int) func() int { + i := initial + return func() int { + i++ + return i + } +} diff --git a/protoc-gen-frisbee/pkg/generator/client.go b/protoc-gen-frisbee/pkg/generator/client.go deleted file mode 100644 index 2147e0e..0000000 --- a/protoc-gen-frisbee/pkg/generator/client.go +++ /dev/null @@ -1,163 +0,0 @@ -/* - Copyright 2022 Loophole Labs - - 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 generator - -import ( - "github.com/loopholelabs/frisbee/protoc-gen-frisbee/internal/utils" - "google.golang.org/protobuf/reflect/protoreflect" -) - -const ( - clientStruct = "Client" - frisbeeClient = "*frisbee.Client" -) - -func writeClientHandlers(f File, services protoreflect.ServiceDescriptors) { - operationIndex := 0 - for i := 0; i < services.Len(); i++ { - service := services.Get(i) - for j := 0; j < service.Methods().Len(); j++ { - method := service.Methods().Get(j) - f.P(tab, "table[", operationIndex+operationOffset, "] = ", handlerSignature, " {") - f.P(tab, tab, tab, "c.inflight", utils.CamelCase(string(method.Name())), "Mu.RLock()") - f.P(tab, tab, tab, "if ch, ok := c.inflight", utils.CamelCase(string(method.Name())), "[incoming.Metadata.Id]; ok {") - f.P(tab, tab, tab, tab, "c.inflight", utils.CamelCase(string(method.Name())), "Mu.RUnlock()") - f.P(tab, tab, tab, tab, "res := New", utils.CamelCase(string(method.Output().FullName())), "()") - f.P(tab, tab, tab, tab, "res.Decode(incoming)") - f.P(tab, tab, tab, tab, "ch <- res") - f.P(tab, tab, tab, "} else {") - f.P(tab, tab, tab, tab, "c.inflight", utils.CamelCase(string(method.Name())), "Mu.RUnlock()") - f.P(tab, tab, tab, "}") - f.P(tab, tab, tab, "return") - f.P(tab, tab, "}") - operationIndex++ - } - } -} - -func writeClientMethod(f File, method protoreflect.MethodDescriptor, operation int) { - f.P("func (c *Client) ", utils.CamelCase(string(method.Name())), "(ctx context.Context, req *", utils.CamelCase(string(method.Input().FullName())), ") (res *", utils.CamelCase(string(method.Output().FullName())), ", err error) {") - f.P(tab, "ch := make(chan *", utils.CamelCase(string(method.Output().FullName())), ", 1)") - f.P(tab, "p := packet.Get()") - f.P(tab, "p.Metadata.Operation = ", operation+operationOffset) - f.P("LOOP:") - f.P(tab, "p.Metadata.Id = c.next", utils.CamelCase(string(method.Name())), ".Load().(uint16)") - f.P(tab, "if !c.next", utils.CamelCase(string(method.Name())), ".CompareAndSwap(p.Metadata.Id, p.Metadata.Id+1) {") - f.P(tab, tab, "goto LOOP") - f.P(tab, "}") - f.P(tab, "req.Encode(p)") - f.P(tab, "p.Metadata.ContentLength = uint32(len(p.Content.B))") - f.P(tab, "c.inflight", utils.CamelCase(string(method.Name())), "Mu.Lock()") - f.P(tab, "c.inflight", utils.CamelCase(string(method.Name())), "[p.Metadata.Id] = ch") - f.P(tab, "c.inflight", utils.CamelCase(string(method.Name())), "Mu.Unlock()") - f.P(tab, "err = c.Client.WritePacket(p)") - f.P(tab, "if err != nil {") - f.P(tab, tab, "packet.Put(p)") - f.P(tab, tab, "return") - f.P(tab, "}") - f.P(tab, "select {") - f.P(tab, "case res = <- ch:") - f.P(tab, tab, "err = res.error") - f.P(tab, "case <- ctx.Done():") - f.P(tab, tab, "err = ctx.Err()") - f.P(tab, "}") - f.P(tab, "c.inflight", utils.CamelCase(string(method.Name())), "Mu.Lock()") - f.P(tab, "delete(c.inflight", utils.CamelCase(string(method.Name())), ", p.Metadata.Id)") - f.P(tab, "c.inflight", utils.CamelCase(string(method.Name())), "Mu.Unlock()") - f.P(tab, "packet.Put(p)") - f.P(tab, "return") - f.P("}") - f.P() -} - -func writeClientIgnoreMethod(f File, method protoreflect.MethodDescriptor, operation int) { - f.P("func (c *Client) ", utils.CamelCase(string(method.Name())), "Ignore(ctx context.Context, req *", utils.CamelCase(string(method.Input().FullName())), ") (err error) {") - f.P(tab, "p := packet.Get()") - f.P(tab, "p.Metadata.Operation = ", operation+operationOffset) - f.P("LOOP:") - f.P(tab, "p.Metadata.Id = c.next", utils.CamelCase(string(method.Name())), ".Load().(uint16)") - f.P(tab, "if !c.next", utils.CamelCase(string(method.Name())), ".CompareAndSwap(p.Metadata.Id, p.Metadata.Id+1) {") - f.P(tab, tab, "goto LOOP") - f.P(tab, "}") - f.P(tab, "req.ignore = true") - f.P(tab, "req.Encode(p)") - f.P(tab, "p.Metadata.ContentLength = uint32(len(p.Content.B))") - f.P(tab, "err = c.Client.WritePacket(p)") - f.P(tab, "packet.Put(p)") - f.P(tab, "return") - f.P("}") - f.P() -} - -func writeClientMethods(f File, services protoreflect.ServiceDescriptors) { - operationIndex := 0 - for i := 0; i < services.Len(); i++ { - service := services.Get(i) - for j := 0; j < service.Methods().Len(); j++ { - method := service.Methods().Get(j) - writeClientMethod(f, method, operationIndex) - writeClientIgnoreMethod(f, method, operationIndex) - operationIndex++ - } - } -} - -func writeClient(f File, services protoreflect.ServiceDescriptors) { - f.P(typeOpen, clientStruct, structOpen) - f.P(tab, frisbeeClient) - for i := 0; i < services.Len(); i++ { - service := services.Get(i) - for j := 0; j < service.Methods().Len(); j++ { - method := service.Methods().Get(j) - f.P(tab, "next", utils.CamelCase(string(method.Name())), " atomic.Value") - f.P(tab, "inflight", utils.CamelCase(string(method.Name())), "Mu sync.RWMutex") - f.P(tab, "inflight", utils.CamelCase(string(method.Name())), space, "map[uint16]chan *", utils.CamelCase(string(method.Output().FullName()))) - } - } - f.P(typeClose) - f.P() - - f.P("func NewClient(tlsConfig *tls.Config, logger *zerolog.Logger) (*Client, error) {") - f.P(tab, "c := new(Client)") - f.P(tab, "table := make(frisbee.HandlerTable)") - writeClientHandlers(f, services) - - f.P(tab, "var err error") - f.P(tab, "if tlsConfig != nil {") - f.P(tab, tab, "c.Client, err = frisbee.NewClient(table, context.Background(), frisbee.WithTLS(tlsConfig), frisbee.WithLogger(logger))") - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return nil, err") - f.P(tab, tab, "}") - f.P(tab, "} else {") - f.P(tab, tab, "c.Client, err = frisbee.NewClient(table, context.Background(), frisbee.WithLogger(logger))") - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return nil, err") - f.P(tab, tab, "}") - f.P(tab, "}") - for i := 0; i < services.Len(); i++ { - service := services.Get(i) - for j := 0; j < service.Methods().Len(); j++ { - method := service.Methods().Get(j) - f.P(tab, "c.next", utils.CamelCase(string(method.Name())), ".Store(uint16(0))") - f.P(tab, "c.inflight", utils.CamelCase(string(method.Name())), " = make(map[uint16]chan *", utils.CamelCase(string(method.Output().FullName())), ")") - } - } - f.P(tab, "return c, nil") - f.P(typeClose) - f.P() - writeClientMethods(f, services) -} diff --git a/protoc-gen-frisbee/pkg/generator/defaults.go b/protoc-gen-frisbee/pkg/generator/defaults.go index 8ec4fe5..3ea6f08 100644 --- a/protoc-gen-frisbee/pkg/generator/defaults.go +++ b/protoc-gen-frisbee/pkg/generator/defaults.go @@ -17,24 +17,11 @@ package generator const ( - extension = ".frisbee.go" - pointer = "*" - tab = "\t" - space = " " - equal = "=" - comma = "," - period = "." - mapSuffix = "Map" - parenthesesOpen = "(" - parenthesesClose = ")" - typeOpen = "type " - typeClose = "}" - slice = "[]" - structOpen = " struct {" - handlerSignature = "func(ctx context.Context, incoming *packet.Packet) (outgoing *packet.Packet, action frisbee.Action)" - packetAnyKind = "packet.AnyKind" -) - -const ( - operationOffset = 10 + extension = ".frisbee.go" + pointer = "*" + space = " " + comma = "," + mapSuffix = "Map" + slice = "[]" + packetAnyKind = "packet.AnyKind" ) diff --git a/protoc-gen-frisbee/pkg/generator/enums.go b/protoc-gen-frisbee/pkg/generator/enums.go deleted file mode 100644 index 60594a4..0000000 --- a/protoc-gen-frisbee/pkg/generator/enums.go +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright 2022 Loophole Labs - - 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 generator - -import ( - "github.com/loopholelabs/frisbee/protoc-gen-frisbee/internal/utils" - "google.golang.org/protobuf/reflect/protoreflect" -) - -const ( - enumType = " uint32" - enumDefinitionOpen = "const (" -) - -func writeEnums(f File, name string, enums protoreflect.EnumValueDescriptors) { - enumName := utils.CamelCase(name) - f.P(typeOpen, enumName, enumType) - f.P() - f.P(enumDefinitionOpen) - for i := 0; i < enums.Len(); i++ { - enum := enums.Get(i) - f.P(tab, utils.CamelCase(string(enum.FullName())), space, equal, space, enumName, parenthesesOpen, i, parenthesesClose) - } - f.P(parenthesesClose) - f.P() -} diff --git a/protoc-gen-frisbee/pkg/generator/generator.go b/protoc-gen-frisbee/pkg/generator/generator.go index 83a0549..488f011 100644 --- a/protoc-gen-frisbee/pkg/generator/generator.go +++ b/protoc-gen-frisbee/pkg/generator/generator.go @@ -17,10 +17,12 @@ package generator import ( + "github.com/loopholelabs/frisbee/protoc-gen-frisbee/internal/utils" "github.com/loopholelabs/frisbee/protoc-gen-frisbee/internal/version" "google.golang.org/protobuf/compiler/protogen" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/pluginpb" + "text/template" ) type Generator struct { @@ -51,42 +53,46 @@ func (g *Generator) Generate(req *pluginpb.CodeGeneratorRequest) (res *pluginpb. return nil, err } + temp := template.Must(template.New("main").Funcs(template.FuncMap{ + "CamelCase": utils.CamelCaseFN, + "CamelCaseN": utils.CamelCaseN, + "MakeIterable": utils.MakeIterable, + "Counter": utils.Counter, + "FirstLowerCase": utils.FirstLowerCase, + "FirstLowerCaseN": utils.FirstLowerCaseN, + "FindValue": findValue, + "GetKind": getKind, + "GetLUTEncoder": getLUTEncoder, + "GetLUTDecoder": getLUTDecoder, + "GetEncodingFields": getEncodingFields, + "GetDecodingFields": getDecodingFields, + "GetKindLUT": getKindLUT, + "GetServerFields": getServerFields, + }).ParseGlob("protoc-gen-frisbee/templates/*")) + for _, f := range plugin.Files { if !f.Generate { continue } genFile := plugin.NewGeneratedFile(fileName(f.GeneratedFilenamePrefix), f.GoImportPath) - writeComment(genFile, version.Version, f.Desc.Path()) - if f.Desc.Package().Name() == "" { - writePackage(genFile, f.GoPackageName) - } else { - writePackage(genFile, protogen.GoPackageName(f.Desc.Package().Name())) - } - writeImports(genFile, requiredImports) - writeErrors(genFile) - for i := 0; i < f.Desc.Enums().Len(); i++ { - enum := f.Desc.Enums().Get(i) - writeEnums(genFile, string(enum.FullName()), enum.Values()) + packageName := string(f.Desc.Package().Name()) + if packageName == "" { + packageName = string(f.GoPackageName) } - for i := 0; i < f.Desc.Messages().Len(); i++ { - message := f.Desc.Messages().Get(i) - message.Options().ProtoReflect() - for i := 0; i < message.Enums().Len(); i++ { - enum := message.Enums().Get(i) - writeEnums(genFile, string(enum.FullName()), enum.Values()) - } - writeStructs(genFile, string(message.FullName()), message.Fields(), message.Messages()) + err = temp.ExecuteTemplate(genFile, "base.go.txt", map[string]interface{}{ + "pluginVersion": version.Version, + "sourcePath": f.Desc.Path(), + "package": f.GoPackageName, + "imports": requiredImports, + "enums": f.Desc.Enums(), + "messages": f.Desc.Messages(), + "services": f.Desc.Services(), + }) + if err != nil { + return nil, err } - - for i := 0; i < f.Desc.Services().Len(); i++ { - service := f.Desc.Services().Get(i) - writeInterface(genFile, string(service.Name()), service.Methods()) - } - - writeServer(genFile, f.Desc.Services()) - writeClient(genFile, f.Desc.Services()) } return plugin.Response(), nil diff --git a/protoc-gen-frisbee/pkg/generator/headers.go b/protoc-gen-frisbee/pkg/generator/headers.go index ad03453..ff0c18d 100644 --- a/protoc-gen-frisbee/pkg/generator/headers.go +++ b/protoc-gen-frisbee/pkg/generator/headers.go @@ -18,34 +18,8 @@ package generator import ( "github.com/loopholelabs/frisbee/protoc-gen-frisbee/internal/utils" - "google.golang.org/protobuf/compiler/protogen" -) - -const ( - commentHeader = "// Code generated by Frisbee " - doNotEditHeader = ", DO NOT EDIT." - sourceHeader = "// source: " - packageHeader = "package " ) func fileName(name string) string { return utils.AppendString(name, extension) } - -func writeComment(f File, version string, source string) { - f.P(commentHeader, version, doNotEditHeader) - f.P(sourceHeader, source) - f.P() -} - -func writePackage(f File, packageName protogen.GoPackageName) { - f.P(packageHeader, packageName) - f.P() -} - -func writeErrors(f File) { - f.P("var (") - f.P(tab, "NilDecode = errors.New(\"cannot decode into a nil root struct\")") - f.P(")") - f.P() -} diff --git a/protoc-gen-frisbee/pkg/generator/imports.go b/protoc-gen-frisbee/pkg/generator/imports.go index d5d3a5f..5d584ee 100644 --- a/protoc-gen-frisbee/pkg/generator/imports.go +++ b/protoc-gen-frisbee/pkg/generator/imports.go @@ -16,10 +16,6 @@ package generator -const ( - importOpenHeader = "import (" -) - var ( requiredImports = []string{ "github.com/loopholelabs/frisbee", @@ -32,13 +28,3 @@ var ( "sync/atomic", } ) - -func writeImports(f File, imports []string) { - f.P() - f.P(importOpenHeader) - for _, im := range imports { - f.P("\t\"", im, "\"") - } - f.P(parenthesesClose) - f.P() -} diff --git a/protoc-gen-frisbee/pkg/generator/interfaces.go b/protoc-gen-frisbee/pkg/generator/interfaces.go deleted file mode 100644 index 0929db4..0000000 --- a/protoc-gen-frisbee/pkg/generator/interfaces.go +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright 2022 Loophole Labs - - 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 generator - -import ( - "github.com/loopholelabs/frisbee/protoc-gen-frisbee/internal/utils" - "google.golang.org/protobuf/reflect/protoreflect" - "strings" -) - -const ( - interfaceOpen = " interface {" - functionNameOpen = "(context.Context, " - functionNameSeparator = ") (" - functionNameClose = ", error)" -) - -func writeInterface(f File, name string, methods protoreflect.MethodDescriptors) { - builder := new(strings.Builder) - f.P(typeOpen, utils.CamelCase(name), interfaceOpen) - for i := 0; i < methods.Len(); i++ { - method := methods.Get(i) - builder.WriteString(pointer) - builder.WriteString(utils.CamelCase(string(method.Input().FullName()))) - - inputType := builder.String() - builder.Reset() - - builder.WriteString(pointer) - builder.WriteString(utils.CamelCase(string(method.Output().FullName()))) - - outputType := builder.String() - builder.Reset() - - f.P(tab, utils.CamelCase(string(method.Name())), functionNameOpen, inputType, functionNameSeparator, outputType, functionNameClose) - } - f.P(typeClose) - f.P() -} diff --git a/protoc-gen-frisbee/pkg/generator/server.go b/protoc-gen-frisbee/pkg/generator/server.go index 9721577..d878af4 100644 --- a/protoc-gen-frisbee/pkg/generator/server.go +++ b/protoc-gen-frisbee/pkg/generator/server.go @@ -22,50 +22,7 @@ import ( "strings" ) -const ( - serverStruct = "Server" - frisbeeServer = "*frisbee.Server" -) - -func writeServerHandlers(f File, services protoreflect.ServiceDescriptors) { - operationIndex := 0 - for i := 0; i < services.Len(); i++ { - service := services.Get(i) - for j := 0; j < service.Methods().Len(); j++ { - method := service.Methods().Get(j) - f.P(tab, "table[", operationIndex+operationOffset, "] = ", handlerSignature, " {") - f.P(tab, tab, tab, "req := New", utils.CamelCase(string(method.Input().FullName())), "()") - f.P(tab, tab, tab, "err := req.Decode(incoming)") - f.P(tab, tab, tab, "if err == nil {") - f.P(tab, tab, tab, tab, "if req.ignore {") - f.P(tab, tab, tab, tab, tab, utils.FirstLowerCase(utils.CamelCase(string(service.Name()))), period, - utils.CamelCase(string(method.Name())), "(ctx, req)") - f.P(tab, tab, tab, tab, "} else {") - f.P(tab, tab, tab, tab, tab, "var res *", utils.CamelCase(string(method.Output().FullName()))) - f.P(tab, tab, tab, tab, tab, "outgoing = incoming") - f.P(tab, tab, tab, tab, tab, "outgoing.Content.Reset()") - f.P(tab, tab, tab, tab, tab, "res, err = ", utils.FirstLowerCase(utils.CamelCase(string(service.Name()))), period, - utils.CamelCase(string(method.Name())), "(ctx, req)") - f.P(tab, tab, tab, tab, tab, "if err != nil {") - f.P(tab, tab, tab, tab, tab, tab, "res.Error(outgoing, err)") - f.P(tab, tab, tab, tab, tab, "} else {") - f.P(tab, tab, tab, tab, tab, tab, "res.Encode(outgoing)") - f.P(tab, tab, tab, tab, tab, "}") - f.P(tab, tab, tab, tab, tab, "outgoing.Metadata.ContentLength = uint32(len(outgoing.Content.B))") - f.P(tab, tab, tab, tab, "}") - f.P(tab, tab, tab, "}") - f.P(tab, tab, tab, "return") - f.P(tab, tab, "}") - operationIndex++ - } - } -} - -func writeServer(f File, services protoreflect.ServiceDescriptors) { - f.P(typeOpen, serverStruct, structOpen) - f.P(tab, frisbeeServer) - f.P(typeClose) - f.P() +func getServerFields(services protoreflect.ServiceDescriptors) string { builder := new(strings.Builder) for i := 0; i < services.Len(); i++ { service := services.Get(i) @@ -78,25 +35,5 @@ func writeServer(f File, services protoreflect.ServiceDescriptors) { } serverFields := builder.String() serverFields = serverFields[:len(serverFields)-2] - f.P("func NewServer(", serverFields, ", tlsConfig *tls.Config, logger *zerolog.Logger) (*Server, error) {") - f.P(tab, "table := make(frisbee.HandlerTable)") - writeServerHandlers(f, services) - - f.P(tab, "var s *frisbee.Server") - f.P(tab, "var err error") - f.P(tab, "if tlsConfig != nil {") - f.P(tab, tab, "s, err = frisbee.NewServer(table, frisbee.WithTLS(tlsConfig), frisbee.WithLogger(logger))") - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return nil, err") - f.P(tab, tab, "}") - f.P(tab, "} else {") - f.P(tab, tab, "s, err = frisbee.NewServer(table, frisbee.WithLogger(logger))") - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return nil, err") - f.P(tab, tab, "}") - f.P("}") - f.P(tab, "return &Server{") - f.P(tab, tab, "Server: s,") - f.P(tab, "}, nil") - f.P(typeClose) + return serverFields } diff --git a/protoc-gen-frisbee/pkg/generator/structs.go b/protoc-gen-frisbee/pkg/generator/structs.go index cbe0942..5e367d6 100644 --- a/protoc-gen-frisbee/pkg/generator/structs.go +++ b/protoc-gen-frisbee/pkg/generator/structs.go @@ -18,14 +18,9 @@ package generator import ( "errors" + "fmt" "github.com/loopholelabs/frisbee/protoc-gen-frisbee/internal/utils" "google.golang.org/protobuf/reflect/protoreflect" - "strings" -) - -const ( - mapOpen = "map[" - mapClose = "]" ) var ( @@ -146,38 +141,17 @@ func findValue(field protoreflect.FieldDescriptor) string { } } -func writeGetFunc(f File, name string, fields protoreflect.FieldDescriptors) { - f.P("func New", utils.CamelCase(name), "() *", utils.CamelCase(name), " {") - f.P(tab, "return &", utils.CamelCase(name), "{") - for i := 0; i < fields.Len(); i++ { - field := fields.Get(i) - if field.Kind() == protoreflect.MessageKind && field.Cardinality() != protoreflect.Repeated { - f.P(tab, tab, utils.CamelCase(string(field.Name())), ": New", utils.CamelCase(string(field.Message().FullName())), "(),") - } - } - f.P(tab, "}") - f.P("}") - f.P() -} - -func writeError(f File, name string) { - f.P("func (x *", utils.CamelCase(name), ") Error(p *packet.Packet, err error) {") - f.P(tab, "packet.Encoder(p).Error(err)") - f.P("}") - f.P() +type encodingFields struct { + MessageFields []protoreflect.FieldDescriptor + SliceFields []protoreflect.FieldDescriptor + Values []string } -func writeEncode(f File, name string, fields protoreflect.FieldDescriptors) { - f.P("func (x *", utils.CamelCase(name), ") Encode(p *packet.Packet) {") - f.P(tab, "if x == nil {") - f.P(tab, tab, "packet.Encoder(p).Nil()") - f.P(tab, "} else if x.error != nil {") - f.P(tab, tab, "packet.Encoder(p).Error(x.error)") - f.P(tab, "} else {") +func getEncodingFields(fields protoreflect.FieldDescriptors) encodingFields { var messageFields []protoreflect.FieldDescriptor var sliceFields []protoreflect.FieldDescriptor - builder := new(strings.Builder) - builder.WriteString(".Bool(x.ignore)") + var values []string + for i := 0; i < fields.Len(); i++ { field := fields.Get(i) if field.Cardinality() == protoreflect.Repeated && !field.IsMap() { @@ -191,213 +165,38 @@ func writeEncode(f File, name string, fields protoreflect.FieldDescriptors) { panic(unknownKind) } } else { - builder.WriteString(encoder) - if field.Kind() == protoreflect.EnumKind { - builder.WriteString("(uint32") - } - builder.WriteString("(x.") - builder.WriteString(utils.CamelCase(string(field.Name()))) - builder.WriteString(")") if field.Kind() == protoreflect.EnumKind { - builder.WriteString(")") + values = append(values, fmt.Sprintf("%s(uint32(x.%s))", encoder, utils.CamelCase(string(field.Name())))) + } else { + values = append(values, fmt.Sprintf("%s(x.%s)", encoder, utils.CamelCase(string(field.Name())))) } } } } - f.P(tab, tab, "packet.Encoder(p)", builder.String()) - writeEncodeSlices(f, sliceFields) - writeEncodeMessages(f, messageFields) - f.P(tab, "}") - f.P("}") - f.P() -} - -func writeEncodeSlices(f File, sliceFields []protoreflect.FieldDescriptor) { - for _, field := range sliceFields { - if encoder, ok := encodeLUT[field.Kind()]; !ok { - switch field.Kind() { - case protoreflect.MessageKind: - f.P(tab, tab, "packet.Encoder(p).Slice(uint32(len(x.", utils.CamelCase(string(field.Name())), ")), ", packetAnyKind, ")") - f.P(tab, tab, "for _, v := range x.", utils.CamelCase(string(field.Name())), " {") - f.P(tab, tab, tab, "v.Encode(p)") - default: - panic(unknownKind) - } - } else { - f.P(tab, tab, "packet.Encoder(p).Slice(uint32(len(x.", utils.CamelCase(string(field.Name())), ")),", kindLUT[field.Kind()], ")") - f.P(tab, tab, "for _, v := range x.", utils.CamelCase(string(field.Name())), " {") - f.P(tab, tab, tab, "packet.Encoder(p)", encoder, "(v)") - } - f.P(tab, tab, "}") - } -} - -func writeEncodeMessages(f File, messageFields []protoreflect.FieldDescriptor) { - for _, field := range messageFields { - f.P(tab, tab, "x.", utils.CamelCase(string(field.Name())), ".Encode(p)") + return encodingFields{ + MessageFields: messageFields, + SliceFields: sliceFields, + Values: values, } } -func writeEncodeMap(f File, field protoreflect.FieldDescriptor) { - f.P("func (x ", utils.CamelCase(string(field.FullName())), mapSuffix, ") Encode(p *packet.Packet) {") - f.P(tab, "if x == nil {") - f.P(tab, tab, "packet.Encoder(p).Nil()") - f.P(tab, "} else {") - var keyKind string - var valKind string - var ok bool - if keyKind, ok = kindLUT[field.MapKey().Kind()]; !ok { - switch field.MapKey().Kind() { - case protoreflect.MessageKind: - keyKind = packetAnyKind - default: - panic(unknownKind) - } - } - - if valKind, ok = kindLUT[field.MapValue().Kind()]; !ok { - switch field.MapValue().Kind() { - case protoreflect.MessageKind: - valKind = packetAnyKind - default: - panic(unknownKind) - } - } - - f.P(tab, tab, "packet.Encoder(p).Map(uint32(len(x)), ", keyKind, ", ", valKind, ")") - f.P(tab, tab, "for k, v := range x {") - if encoder, ok := encodeLUT[field.MapKey().Kind()]; !ok { - switch field.MapKey().Kind() { - case protoreflect.MessageKind: - f.P(tab, tab, tab, "k.Encode(p)") - default: - panic(unknownKind) - } - } else { - if field.MapKey().Kind() == protoreflect.EnumKind { - f.P(tab, tab, tab, "packet.Encoder(p)", encoder, "(uint32(k))") - } else { - f.P(tab, tab, tab, "packet.Encoder(p)", encoder, "(k)") - } - } - - if encoder, ok := encodeLUT[field.MapValue().Kind()]; !ok { - switch field.MapValue().Kind() { - case protoreflect.MessageKind: - f.P(tab, tab, tab, "v.Encode(p)") - default: - panic(unknownKind) - } - } else { - if field.MapValue().Kind() == protoreflect.EnumKind { - f.P(tab, tab, tab, "packet.Encoder(p)", encoder, "(uint32(v))") - } else { - f.P(tab, tab, tab, "packet.Encoder(p)", encoder, "(v)") - } - } - f.P(tab, tab, "}") - f.P(tab, tab, tab, "") - f.P(tab, "}") - f.P("}") - f.P() +type decodingFields struct { + MessageFields []protoreflect.FieldDescriptor + SliceFields []protoreflect.FieldDescriptor + Other []protoreflect.FieldDescriptor } -func writeDecodeMap(f File, field protoreflect.FieldDescriptor) { - f.P("func (x ", utils.CamelCase(string(field.FullName())), mapSuffix, ") decode(d *packet.Decoder, size uint32) error {") - f.P(tab, "if size == 0 {") - f.P(tab, tab, "return nil") - f.P(tab, "}") - f.P(tab, "var k ", findValue(field.MapKey())) - if field.MapKey().Kind() == protoreflect.EnumKind { - f.P(tab, tab, "var ", utils.CamelCase(string(field.MapKey().Name())), "Temp uint32") - } - f.P(tab, "var v ", findValue(field.MapValue())) - if field.MapValue().Kind() == protoreflect.EnumKind { - f.P(tab, tab, "var ", utils.CamelCase(string(field.MapValue().Name())), "Temp uint32") - } - f.P(tab, "var err error") - f.P(tab, "for i := uint32(0); i < size; i++ {") - - if decoder, ok := decodeLUT[field.MapKey().Kind()]; !ok { - switch field.MapKey().Kind() { - case protoreflect.MessageKind: - f.P(tab, tab, "k = New", utils.CamelCase(string(field.MapKey().Message().FullName())), "()") - f.P(tab, tab, "err = k.decode(d)") - default: - panic(unknownKind) - } - } else { - if field.MapKey().Kind() == protoreflect.EnumKind { - f.P(tab, tab, utils.CamelCase(string(field.MapKey().Name())), "Temp, err = d", decoder, "()") - f.P(tab, tab, "k = ", findValue(field.MapKey()), "(", utils.CamelCase(string(field.MapKey().Name())), "Temp)") - } else { - f.P(tab, tab, "k, err = d", decoder, "()") - } - } - - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return err") - f.P(tab, tab, "}") - - if decoder, ok := decodeLUT[field.MapValue().Kind()]; !ok { - switch field.MapValue().Kind() { - case protoreflect.MessageKind: - f.P(tab, tab, "v = New", utils.CamelCase(string(field.MapValue().Message().FullName())), "()") - f.P(tab, tab, "err = v.decode(d)") - default: - panic(unknownKind) - } - } else { - if field.MapValue().Kind() == protoreflect.EnumKind { - f.P(tab, tab, utils.CamelCase(string(field.MapValue().Name())), "Temp, err = d", decoder, "()") - f.P(tab, tab, "v = ", findValue(field.MapValue()), "(", utils.CamelCase(string(field.MapValue().Name())), "Temp)") - } else { - f.P(tab, tab, "v, err = d", decoder, "()") - } - } - - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return err") - f.P(tab, tab, "}") - - f.P(tab, tab, "x[k] = v") - f.P(tab, "}") - f.P(tab, "return nil") - f.P("}") - f.P() -} - -func writeDecode(f File, name string) { - f.P("func (x *", utils.CamelCase(name), ") Decode(p *packet.Packet) error {") - f.P(tab, "if x == nil {") - f.P(tab, tab, "return NilDecode") - f.P(tab, "}") - f.P(tab, "d := packet.GetDecoder(p)") - f.P(tab, "return x.decode(d)") - f.P("}") - f.P() -} - -func writeInternalDecode(f File, name string, fields protoreflect.FieldDescriptors) { - f.P("func (x *", utils.CamelCase(name), ") decode(d *packet.Decoder) error {") - f.P(tab, "if d.Nil() {") - f.P(tab, tab, "return nil") - f.P(tab, "}") - f.P(tab, "var err error") - f.P(tab, "x.error, err = d.Error()") - f.P(tab, "if err != nil {") - f.P(tab, tab, "x.ignore, err = d.Bool()") - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return err") - f.P(tab, tab, "}") +func getDecodingFields(fields protoreflect.FieldDescriptors) decodingFields { var messageFields []protoreflect.FieldDescriptor var sliceFields []protoreflect.FieldDescriptor + var other []protoreflect.FieldDescriptor + for i := 0; i < fields.Len(); i++ { field := fields.Get(i) if field.Cardinality() == protoreflect.Repeated && !field.IsMap() { sliceFields = append(sliceFields, field) } else { - if decoder, ok := decodeLUT[field.Kind()]; !ok { + if _, ok := decodeLUT[field.Kind()]; !ok { switch field.Kind() { case protoreflect.MessageKind: messageFields = append(messageFields, field) @@ -405,150 +204,40 @@ func writeInternalDecode(f File, name string, fields protoreflect.FieldDescripto panic(unknownKind) } } else { - if field.Kind() == protoreflect.BytesKind { - decoder += "(nil)" - } else { - decoder += "()" - } - if field.Kind() == protoreflect.EnumKind { - f.P(tab, tab, "var ", utils.CamelCase(string(field.Name())), "Temp uint32") - f.P(tab, tab, utils.CamelCase(string(field.Name())), "Temp, err = d", decoder) - f.P(tab, tab, "x.", utils.CamelCase(string(field.Name())), " = ", findValue(field), "(", utils.CamelCase(string(field.Name())), "Temp)") - } else { - f.P(tab, tab, "x.", utils.CamelCase(string(field.Name())), ", err = d", decoder) - } - - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return err") - f.P(tab, tab, "}") + other = append(other, field) } } } - if len(sliceFields) > 0 { - f.P(tab, tab, "var sliceSize uint32") - } - for _, field := range sliceFields { - var kind string - var ok bool - if kind, ok = kindLUT[field.Kind()]; !ok { - switch field.Kind() { - case protoreflect.MessageKind: - kind = packetAnyKind - default: - panic(unknownKind) - } - } - f.P(tab, tab, "sliceSize, err = d.Slice(", kind, ")") - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return err") - f.P(tab, tab, "}") - f.P(tab, tab, "if uint32(len(x.", utils.CamelCase(string(field.Name())), ")) != sliceSize {") - f.P(tab, tab, tab, "x.", utils.CamelCase(string(field.Name())), " = make(", findValue(field), ", sliceSize)") - f.P(tab, tab, "}") - f.P(tab, tab, "for i := uint32(0); i < sliceSize; i++ {") - if decoder, ok := decodeLUT[field.Kind()]; !ok { - switch field.Kind() { - case protoreflect.MessageKind: - f.P(tab, tab, tab, "err = x.", utils.CamelCase(string(field.Name())), "[i].decode(d)") - default: - panic(unknownKind) - } - } else { - f.P(tab, tab, tab, "x.", utils.CamelCase(string(field.Name())), "[i], err = d", decoder, "()") - } - f.P(tab, tab, tab, "if err != nil {") - f.P(tab, tab, tab, tab, "return err") - f.P(tab, tab, tab, "}") - f.P(tab, tab, "}") - } - for _, field := range messageFields { - if field.IsMap() { - f.P(tab, tab, "if !d.Nil() {") - var keyKind string - var valKind string - var ok bool - if keyKind, ok = kindLUT[field.MapKey().Kind()]; !ok { - switch field.Kind() { - case protoreflect.MessageKind: - keyKind = packetAnyKind - default: - panic(unknownKind) - } - } - if valKind, ok = kindLUT[field.MapValue().Kind()]; !ok { - switch field.Kind() { - case protoreflect.MessageKind: - valKind = packetAnyKind - default: - panic(unknownKind) - } - } - f.P(tab, tab, utils.CamelCase(string(field.Name())), "Size, err := d.Map(", keyKind, ", ", valKind, ")") - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return err") - f.P(tab, tab, "}") - f.P(tab, tab, "x.", utils.CamelCase(string(field.Name())), " = New", utils.CamelCase(string(field.FullName())), mapSuffix, "(", utils.CamelCase(string(field.Name())), "Size)") - f.P(tab, tab, "err = x.", utils.CamelCase(string(field.Name())), ".decode(d, ", utils.CamelCase(string(field.Name())), "Size)") - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return err") - f.P(tab, tab, "}") - f.P(tab, "}") - } else { - f.P(tab, tab, "if x.", utils.CamelCase(string(field.Name())), " == nil {") - f.P(tab, tab, tab, "x.", utils.CamelCase(string(field.Name())), " = New", utils.CamelCase(string(field.Message().FullName())), "()") - f.P(tab, tab, "}") - f.P(tab, tab, "err = x.", utils.CamelCase(string(field.Name())), ".decode(d)") - f.P(tab, tab, "if err != nil {") - f.P(tab, tab, tab, "return err") - f.P(tab, tab, "}") - } + return decodingFields{ + MessageFields: messageFields, + SliceFields: sliceFields, + Other: other, } - f.P(tab, "}") - f.P(tab, "d.Return()") - f.P(tab, "return nil") - f.P("}") - f.P() } -func writeStructs(f File, name string, fields protoreflect.FieldDescriptors, messages protoreflect.MessageDescriptors) { - for i := 0; i < messages.Len(); i++ { - message := messages.Get(i) - if !message.IsMapEntry() { - writeStructs(f, string(message.FullName()), message.Fields(), message.Messages()) - } - } - for i := 0; i < fields.Len(); i++ { - field := fields.Get(i) - if field.IsMap() { - mapKeyValue := findValue(field.MapKey()) - mapValueValue := findValue(field.MapValue()) - f.P(typeOpen, utils.CamelCase(string(field.FullName())), mapSuffix, space, mapOpen, mapKeyValue, mapClose, mapValueValue) - f.P() - f.P("func New", utils.CamelCase(string(field.FullName())), mapSuffix, "(size uint32) ", mapOpen, mapKeyValue, mapClose, mapValueValue, " {") - f.P(tab, "return make(", mapOpen, mapKeyValue, mapClose, mapValueValue, ", size)") - f.P("}") - f.P() - writeEncodeMap(f, field) - writeDecodeMap(f, field) +func getKind(kind protoreflect.Kind) string { + var outKind string + var ok bool + if outKind, ok = kindLUT[kind]; !ok { + switch kind { + case protoreflect.MessageKind: + outKind = packetAnyKind + default: + panic(unknownKind) } } - f.P(typeOpen, utils.CamelCase(name), structOpen) - f.P(tab, "error error") - f.P(tab, "ignore bool") - f.P() + return outKind +} - for i := 0; i < fields.Len(); i++ { - field := fields.Get(i) - value := findValue(field) - f.P(tab, utils.CamelCase(string(field.Name())), space, value) - } - f.P(typeClose) - f.P() +func getLUTEncoder(kind protoreflect.Kind) string { + return encodeLUT[kind] +} + +func getLUTDecoder(kind protoreflect.Kind) string { + return decodeLUT[kind] +} - writeGetFunc(f, name, fields) - writeError(f, name) - writeEncode(f, name, fields) - writeDecode(f, name) - writeInternalDecode(f, name, fields) +func getKindLUT(kind protoreflect.Kind) string { + return kindLUT[kind] } diff --git a/protoc-gen-frisbee/templates/base.go.txt b/protoc-gen-frisbee/templates/base.go.txt new file mode 100644 index 0000000..7b67c00 --- /dev/null +++ b/protoc-gen-frisbee/templates/base.go.txt @@ -0,0 +1,17 @@ +{{template "headers" .}} + +{{template "imports" .}} + +var ( + NilDecode = errors.New("cannot decode into a nil root struct") +) + +{{template "enums" .}} + +{{template "messages" .}} + +{{template "interfaces" .}} + +{{template "server" .}} + +{{template "client" .}} \ No newline at end of file diff --git a/protoc-gen-frisbee/templates/client.go.txt b/protoc-gen-frisbee/templates/client.go.txt new file mode 100644 index 0000000..7da2b50 --- /dev/null +++ b/protoc-gen-frisbee/templates/client.go.txt @@ -0,0 +1,126 @@ +{{define "client"}} +type Client struct { + *frisbee.Client + {{ range $i, $v := (MakeIterable .services.Len) -}} + {{ $service := $.services.Get $i -}} + {{ range $i, $v := (MakeIterable $service.Methods.Len) -}} + {{ $method := $service.Methods.Get $i -}} + next{{ CamelCaseN $method.Name }} atomic.Value + inflight{{ CamelCaseN $method.Name }}Mu sync.RWMutex + inflight{{ CamelCaseN $method.Name }} map[uint16]chan *{{ CamelCase $method.Output.FullName }} + {{end -}} + {{end -}} +} + +func NewClient (tlsConfig *tls.Config, logger *zerolog.Logger) (*Client, error) { + c := new(Client) + table := make(frisbee.HandlerTable) + {{template "clienthandlers" .services -}} + + var err error + if tlsConfig != nil { + c.Client, err = frisbee.NewClient(table, context.Background(), frisbee.WithTLS(tlsConfig), frisbee.WithLogger(logger)) + if err != nil { + return nil, err + } + } else { + c.Client, err = frisbee.NewClient(table, context.Background(), frisbee.WithLogger(logger)) + if err != nil { + return nil, err + } + } + + {{ range $i, $v := (MakeIterable .services.Len) -}} + {{ $service := $.services.Get $i -}} + {{ range $i, $v := (MakeIterable $service.Methods.Len) -}} + {{ $method := $service.Methods.Get $i -}} + c.next{{ CamelCaseN $method.Name }}.Store(uint16(0)) + c.inflight{{ CamelCaseN $method.Name }} = make(map[uint16]chan *{{ CamelCase $method.Output.FullName }}) + {{end -}} + {{end -}} + return c, nil +} + +{{template "clientmethods" .services }} +{{end}} + +{{define "clienthandlers"}} +{{ $counter := Counter 9 -}} +{{ range $i, $v := (MakeIterable .Len) }} + {{ $service := $.Get $i -}} + {{ range $i, $v := (MakeIterable $service.Methods.Len) -}} + {{ $method := $service.Methods.Get $i -}} + {{ $count := call $counter -}} + table[{{ $count }}] = func(ctx context.Context, incoming *packet.Packet) (outgoing *packet.Packet, action frisbee.Action) { + c.inflight{{ CamelCaseN $method.Name }}Mu.RLock() + if ch, ok := c.inflight{{ CamelCaseN $method.Name }}[incoming.Metadata.Id]; ok { + c.inflight{{ CamelCaseN $method.Name }}Mu.RUnlock() + res := New{{ CamelCase $method.Output.FullName }}() + res.Decode(incoming) + ch <- res + } else { + c.inflight{{ CamelCaseN $method.Name }}Mu.RUnlock() + } + return + } + {{end -}} +{{end -}} +{{end}} + +{{define "clientmethods"}} +{{ $counter := Counter 9 -}} +{{ range $i, $v := (MakeIterable .Len) -}} + {{ $service := $.Get $i -}} + {{ range $i, $v := (MakeIterable $service.Methods.Len) }} + {{ $method := $service.Methods.Get $i -}} + {{ $opIndex := call $counter -}} + func (c *Client) {{ CamelCaseN $method.Name }}(ctx context.Context, req *{{ CamelCase $method.Input.FullName }}) (res *{{ CamelCase $method.Output.FullName }}, err error) { + ch := make(chan *{{ CamelCase $method.Output.FullName }}, 1) + p := packet.Get() + p.Metadata.Operation = {{ $opIndex }} + LOOP: + p.Metadata.Id = c.next{{ CamelCaseN $method.Name }}.Load().(uint16) + if !c.next{{ CamelCaseN $method.Name }}.CompareAndSwap(p.Metadata.Id, p.Metadata.Id+1) { + goto LOOP + } + req.Encode(p) + p.Metadata.ContentLength = uint32(len(p.Content.B)) + c.inflight{{ CamelCaseN $method.Name }}Mu.Lock() + c.inflight{{ CamelCaseN $method.Name }}[p.Metadata.Id] = ch + c.inflight{{ CamelCaseN $method.Name }}Mu.Unlock() + err = c.Client.WritePacket(p) + if err != nil { + packet.Put(p) + return + } + select { + case res = <- ch: + err = res.error + case <- ctx.Done(): + err = ctx.Err() + } + c.inflight{{ CamelCaseN $method.Name }}Mu.Lock() + delete(c.inflight{{ CamelCaseN $method.Name }}, p.Metadata.Id) + c.inflight{{ CamelCaseN $method.Name }}Mu.Unlock() + packet.Put(p) + return + } + + func (c *Client) {{ CamelCaseN $method.Name }}Ignore(ctx context.Context, req *{{ CamelCase $method.Input.FullName }}) (err error) { + p := packet.Get() + p.Metadata.Operation = {{ $opIndex }} + LOOP: + p.Metadata.Id = c.next{{ CamelCaseN $method.Name }}.Load().(uint16) + if !c.next{{ CamelCaseN $method.Name }}.CompareAndSwap(p.Metadata.Id, p.Metadata.Id+1) { + goto LOOP + } + req.ignore = true + req.Encode(p) + p.Metadata.ContentLength = uint32(len(p.Content.B)) + err = c.Client.WritePacket(p) + packet.Put(p) + return + } + {{end -}} +{{end -}} +{{end}} diff --git a/protoc-gen-frisbee/templates/decode.go.txt b/protoc-gen-frisbee/templates/decode.go.txt new file mode 100644 index 0000000..53d2fef --- /dev/null +++ b/protoc-gen-frisbee/templates/decode.go.txt @@ -0,0 +1,94 @@ +{{define "decode"}} +func (x *{{ CamelCase .FullName }}) Decode (p *packet.Packet) error { + if x == nil { + return NilDecode + } + d := packet.GetDecoder(p) + return x.decode(d) +} +{{end}} + +{{define "internalDecode"}} +func (x *{{CamelCase .FullName}}) decode(d *packet.Decoder) error { + if d.Nil() { + return nil + } + var err error + x.error, err = d.Error() + if err != nil { + x.ignore, err = d.Bool() + if err != nil { + return err + } + {{ $decoding := GetDecodingFields .Fields -}} + {{ range $field := $decoding.Other -}} + {{ $decoder := GetLUTDecoder $field.Kind -}} + {{ if eq $field.Kind 12 -}} {{/* protoreflect.BytesKind */ -}} + x.{{ CamelCaseN $field.Name }}, err = d{{ $decoder }}(nil) + {{ else if eq $field.Kind 14 -}} {{/* protoreflect.EnumKind */ -}} + var {{ CamelCaseN $field.Name }}Temp uint32 + {{ CamelCaseN $field.Name }}Temp, err = d{{ $decoder }}() + x.{{ CamelCaseN $field.Name }} = {{ FindValue $field }}({{ CamelCaseN $field.Name }}Temp) + {{ else -}} + x.{{ CamelCaseN $field.Name }}, err = d{{ $decoder }}() + {{end -}} + if err != nil { + return err + } + {{end -}} + + {{ if $decoding.SliceFields -}} + var sliceSize uint32 + {{end -}} + {{ range $field := $decoding.SliceFields -}} + {{ $kind := GetKind $field.Kind -}} + sliceSize, err = d.Slice({{ $kind }}) + if err != nil { + return err + } + if uint32(len(x.{{ CamelCaseN $field.Name }})) != sliceSize { + x.{{ CamelCaseN $field.Name }} = make({{ FindValue $field }}, sliceSize) + } + for i := uint32(0); i < sliceSize; i++ { + {{ $decoder := GetLUTDecoder $field.Kind -}} + {{ if eq $field.Kind 11 -}} {{/* protoreflect.MessageKind */ -}} + err = x.{{ CamelCaseN $field.Name }}[i].decode(d) + {{ else -}} + x.{{ CamelCaseN $field.Name }}[i], err = d{{ $decoder }}() + {{end -}} + if err != nil { + return err + } + } + {{end -}} + {{ range $field := $decoding.MessageFields -}} + {{ if $field.IsMap -}} + if !d.Nil() { + {{ $keyKind := GetKind $field.MapKey.Kind -}} + {{ $valKind := GetKind $field.MapValue.Kind -}} + + {{ CamelCaseN $field.Name }}Size, err := d.Map({{ $keyKind }}, {{ $valKind }}) + if err != nil { + return err + } + x.{{ CamelCaseN $field.Name }} = New{{ CamelCase $field.FullName }}Map({{ CamelCaseN $field.Name }}Size) + err = x.{{ CamelCaseN $field.Name }}.decode(d, {{ CamelCaseN $field.Name }}Size) + if err != nil { + return err + } + } + {{ else -}} + if x.{{ CamelCaseN $field.Name }} == nil { + x.{{ CamelCaseN $field.Name }} = New{{ CamelCase $field.Message.FullName }}() + } + err = x.{{ CamelCaseN $field.Name }}.decode(d) + if err != nil { + return err + } + {{end -}} + {{end -}} + } + d.Return() + return nil +} +{{end}} \ No newline at end of file diff --git a/protoc-gen-frisbee/templates/decodeMap.go.txt b/protoc-gen-frisbee/templates/decodeMap.go.txt new file mode 100644 index 0000000..64f143a --- /dev/null +++ b/protoc-gen-frisbee/templates/decodeMap.go.txt @@ -0,0 +1,51 @@ +{{define "decodeMap"}} +func (x {{CamelCase .FullName}}Map) decode(d *packet.Decoder, size uint32) error { + if size == 0 { + return nil + } + var k {{ FindValue .MapKey }} + {{ if eq .MapKey.Kind 14 -}} {{/* protoreflect.EnumKind */ -}} + var {{ CamelCase .MapKey.Name }}Temp uint32 + {{end -}} + var v {{ FindValue .MapValue }} + {{ if eq .MapValue.Kind 14 -}} {{/* protoreflect.EnumKind */ -}} + var {{ CamelCaseN .MapValue.Name }}Temp uint32 + {{end -}} + var err error + for i := uint32(0); i < size; i++ { + {{ $keyDecoder := GetLUTDecoder .MapKey.Kind -}} + {{ if and (eq $keyDecoder "") (eq .MapKey.Kind 11) -}} {{/* protoreflect.MessageKind */ -}} + k = New{{ CamelCase .MapKey.Message.FullName }}() + err = k.decode(d) + {{else -}} + {{ if eq .MapKey.Kind 14 -}} {{/* protoreflect.EnumKind */ -}} + {{ CamelCase .MapKey.Name }}Temp, err = d{{$keyDecoder}}() + k = {{ FindValue .MapKey }}({{ CamelCase .MapKey.Name }}Temp) + {{else -}} + k, err = d{{$keyDecoder}}() + {{end -}} + {{end -}} + if err != nil { + return err + } + {{ $valDecoder := GetLUTDecoder .MapValue.Kind -}} + {{ if and (eq $valDecoder "") (eq .MapValue.Kind 11) -}} {{/* protoreflect.MessageKind */ -}} + v = New{{ CamelCase .MapValue.Message.FullName }}() + err = v.decode(d) + {{else -}} + {{ if eq .MapValue.Kind 14 -}} {{/* protoreflect.EnumKind */ -}} + {{CamelCaseN .MapValue.Name}}Temp, err = d{{$valDecoder}}() + v = {{ FindValue .MapValue }}({{ CamelCaseN .MapValue.Name }}Temp) + {{else -}} + v, err = d{{$valDecoder}}() + {{end -}} + {{end -}} + + if err != nil { + return err + } + x[k] = v + } + return nil +} +{{end}} \ No newline at end of file diff --git a/protoc-gen-frisbee/templates/encode.go.txt b/protoc-gen-frisbee/templates/encode.go.txt new file mode 100644 index 0000000..4e92c72 --- /dev/null +++ b/protoc-gen-frisbee/templates/encode.go.txt @@ -0,0 +1,41 @@ +{{define "encode"}} +func (x *{{ CamelCase .FullName }}) Encode (p *packet.Packet) { + if x == nil { + packet.Encoder(p).Nil() + } else if x.error != nil { + packet.Encoder(p).Error(x.error) + } else { + {{ $encoding := GetEncodingFields .Fields -}} + packet.Encoder(p).Bool(x.ignore){{ range $val := $encoding.Values -}}{{ $val -}}{{end -}} + {{ if $encoding.SliceFields -}} + {{template "encodeSlices" $encoding -}} + {{end -}} + {{ if $encoding.MessageFields -}} + {{template "encodeMessages" $encoding -}} + {{end -}} + } +} +{{end}} + +{{define "encodeSlices"}} + {{ range $field := .SliceFields -}} + {{ $encoder := GetLUTEncoder $field.Kind -}} + {{ if and (eq $encoder "") (eq $field.Kind 11) -}} {{/* protoreflect.MessageKind */ -}} + packet.Encoder(p).Slice(uint32(len(x.{{ CamelCaseN $field.Name }})), packet.AnyKind) + for _, v := range x.{{CamelCaseN $field.Name}} { + v.Encode(p) + } + {{else -}} + packet.Encoder(p).Slice(uint32(len(x.{{ CamelCaseN $field.Name }})), {{ GetKindLUT $field.Kind }}) + for _, v := range x.{{ CamelCaseN $field.Name }} { + packet.Encoder(p){{$encoder}}(v) + } + {{end -}} + {{end -}} +{{end}} + +{{define "encodeMessages"}} + {{ range $field := .MessageFields -}} + x.{{ CamelCaseN $field.Name }}.Encode(p) + {{end -}} +{{end}} \ No newline at end of file diff --git a/protoc-gen-frisbee/templates/encodeMap.go.txt b/protoc-gen-frisbee/templates/encodeMap.go.txt new file mode 100644 index 0000000..c25ffe9 --- /dev/null +++ b/protoc-gen-frisbee/templates/encodeMap.go.txt @@ -0,0 +1,33 @@ +{{define "encodeMap"}} + func (x {{ CamelCase .FullName }}Map) Encode (p *packet.Packet) { + if x == nil { + packet.Encoder(p).Nil() + } else { + {{ $keyKind := GetKind .MapKey.Kind -}} + {{ $valKind := GetKind .MapValue.Kind -}} + packet.Encoder(p).Map(uint32(len(x)), {{$keyKind}}, {{$valKind}}) + for k, v := range x { + {{ $keyEncoder := GetLUTEncoder .MapKey.Kind -}} + {{ if and (eq $keyEncoder "") (eq .MapKey.Kind 11) -}} {{/* protoreflect.MessageKind */ -}} + k.Encode(p) + {{else -}} + {{ if eq .MapKey.Kind 14 -}} {{/* protoreflect.EnumKind */ -}} + packet.Encoder(p) {{$keyEncoder}} (uint32(k)) + {{else -}} + packet.Encoder(p) {{$keyEncoder}} (k) + {{end -}} + {{end -}} + {{ $valEncoder := GetLUTEncoder .MapValue.Kind -}} + {{ if and (eq $valEncoder "") (eq .MapValue.Kind 11) -}} {{/* protoreflect.MessageKind */ -}} + v.Encode(p) + {{else -}} + {{ if eq .MapValue.Kind 14 -}} {{/* protoreflect.EnumKind */ -}} + packet.Encoder(p) {{$valEncoder}} (uint32(v)) + {{else -}} + packet.Encoder(p) {{$valEncoder}} (v) + {{end -}} + {{end -}} + } + } + } +{{end}} diff --git a/protoc-gen-frisbee/templates/enums.go.txt b/protoc-gen-frisbee/templates/enums.go.txt new file mode 100644 index 0000000..18cd31a --- /dev/null +++ b/protoc-gen-frisbee/templates/enums.go.txt @@ -0,0 +1,19 @@ +{{define "enums"}} +{{range $i, $e := (MakeIterable .enums.Len) -}} +{{ $enum := ($.enums.Get $i) }} +{{template "enum" $enum}} +{{end -}} +{{end}} + +{{define "enum"}} +{{ $enumName := (CamelCase $.FullName) }} +type {{ $enumName }} uint32 + +const ( +{{range $i, $v := (MakeIterable $.Values.Len) -}} + {{ $val := ($.Values.Get $i) -}} + {{CamelCase $val.FullName}} = {{ $enumName }}({{ $i }}) +{{end -}} +) +{{end}} + diff --git a/protoc-gen-frisbee/templates/headers.go.txt b/protoc-gen-frisbee/templates/headers.go.txt new file mode 100644 index 0000000..85785ce --- /dev/null +++ b/protoc-gen-frisbee/templates/headers.go.txt @@ -0,0 +1,6 @@ +{{define "headers"}} +// Code generated by Frisbee {{ .pluginVersion }}, DO NOT EDIT. +// source: {{ .sourcePath }} + +package {{ .package }} +{{end}} \ No newline at end of file diff --git a/protoc-gen-frisbee/templates/imports.go.txt b/protoc-gen-frisbee/templates/imports.go.txt new file mode 100644 index 0000000..6179937 --- /dev/null +++ b/protoc-gen-frisbee/templates/imports.go.txt @@ -0,0 +1,7 @@ +{{define "imports"}} +import ( +{{range $im := .imports -}} + "{{$im}}" +{{end -}} +) +{{end}} \ No newline at end of file diff --git a/protoc-gen-frisbee/templates/interfaces.go.txt b/protoc-gen-frisbee/templates/interfaces.go.txt new file mode 100644 index 0000000..c3f8f87 --- /dev/null +++ b/protoc-gen-frisbee/templates/interfaces.go.txt @@ -0,0 +1,16 @@ +{{define "interfaces"}} +{{range $i, $v := (MakeIterable .services.Len) -}} +{{ $service := ($.services.Get $i) -}} +{{template "interface" $service}} +{{end -}} +{{end}} + + +{{define "interface"}} +type {{ CamelCaseN .Name }} interface { + {{ range $i, $v := MakeIterable .Methods.Len -}} + {{ $method := $.Methods.Get $i -}} + {{ CamelCaseN $method.Name }} (context.Context, *{{ CamelCase $method.Input.FullName }}) (*{{ CamelCase $method.Output.FullName }}, error) + {{ end -}} +} +{{end}} \ No newline at end of file diff --git a/protoc-gen-frisbee/templates/messages.go.txt b/protoc-gen-frisbee/templates/messages.go.txt new file mode 100644 index 0000000..1c8c74b --- /dev/null +++ b/protoc-gen-frisbee/templates/messages.go.txt @@ -0,0 +1,10 @@ +{{define "messages"}} +{{range $i, $e := (MakeIterable .messages.Len) -}} + {{ $message := $.messages.Get $i }} + {{range $i, $e := (MakeIterable $message.Enums.Len) -}} + {{ $enum := ($message.Enums.Get $i) }} + {{template "enum" $enum}} + {{end}} + {{template "structs" $message}} +{{end}} +{{end}} \ No newline at end of file diff --git a/protoc-gen-frisbee/templates/server.go.txt b/protoc-gen-frisbee/templates/server.go.txt new file mode 100644 index 0000000..19b6257 --- /dev/null +++ b/protoc-gen-frisbee/templates/server.go.txt @@ -0,0 +1,57 @@ +{{define "server"}} +type Server struct { + *frisbee.Server +} + func NewServer({{ GetServerFields .services }}, tlsConfig *tls.Config, logger *zerolog.Logger) (*Server, error) { + table := make(frisbee.HandlerTable) + {{template "serverhandlers" .services -}} + var s *frisbee.Server + var err error + if tlsConfig != nil { + s, err = frisbee.NewServer(table, frisbee.WithTLS(tlsConfig), frisbee.WithLogger(logger)) + if err != nil { + return nil, err + } + } else { + s, err = frisbee.NewServer(table, frisbee.WithLogger(logger)) + if err != nil { + return nil, err + } + } + return &Server{ + Server: s, + }, nil + } +{{end}} + +{{define "serverhandlers"}} + {{ $counter := Counter 9 -}} + {{ range $i, $v := (MakeIterable .Len) -}} + {{ $service := $.Get $i -}} + {{ range $i, $v := (MakeIterable $service.Methods.Len) -}} + {{ $method := $service.Methods.Get $i -}} + {{ $count := call $counter -}} + table[{{ $count }}] = func(ctx context.Context, incoming *packet.Packet) (outgoing *packet.Packet, action frisbee.Action) { + req := New{{ CamelCase $method.Input.FullName }}() + err := req.Decode(incoming) + if err == nil { + if req.ignore { + {{ FirstLowerCaseN $service.Name }}.{{ CamelCaseN $method.Name }}(ctx, req) + } else { + var res *{{ CamelCase $method.Output.FullName }} + outgoing = incoming + outgoing.Content.Reset() + res, err = {{ FirstLowerCase (CamelCaseN $service.Name) }}.{{ CamelCaseN $method.Name }}(ctx, req) + if err != nil { + res.Error(outgoing, err) + } else { + res.Encode(outgoing) + } + outgoing.Metadata.ContentLength = uint32(len(outgoing.Content.B)) + } + } + return + } + {{end -}} + {{end -}} +{{end}} \ No newline at end of file diff --git a/protoc-gen-frisbee/templates/structs.go.txt b/protoc-gen-frisbee/templates/structs.go.txt new file mode 100644 index 0000000..b796b01 --- /dev/null +++ b/protoc-gen-frisbee/templates/structs.go.txt @@ -0,0 +1,57 @@ +{{define "structs"}} + {{ range $i, $v := (MakeIterable $.Messages.Len) }} + {{ $message := $.Messages.Get $i }} + {{ if not $message.IsMapEntry }} + {{template "structs" $message}} + {{end}} + {{end}} + {{ range $i, $v := (MakeIterable $.Fields.Len) -}} + {{ $field := $.Fields.Get $i }} + {{ if $field.IsMap }} + {{ $mapKeyValue := FindValue $field.MapKey }} + {{ $mapValueValue := FindValue $field.MapValue }} + type {{ CamelCase $field.FullName }}Map map[{{ $mapKeyValue }}]{{ $mapValueValue }} + func New{{ CamelCase $field.FullName }}Map (size uint32) map[{{ $mapKeyValue }}]{{$mapValueValue}} { + return make(map[{{ $mapKeyValue }}]{{ $mapValueValue }}, size) + } + + {{template "encodeMap" $field}} + {{template "decodeMap" $field}} + {{end}} + {{end -}} + type {{ CamelCase .FullName }} struct { + error error + ignore bool + + {{ range $i, $v := (MakeIterable $.Fields.Len) -}} + {{ $field := $.Fields.Get $i -}} + {{ $value := FindValue $field -}} + {{ CamelCaseN $field.Name }} {{ $value }} + {{end -}} + } + + {{template "getFunc" .}} + {{template "error" .}} + {{template "encode" .}} + {{template "decode" .}} + {{template "internalDecode" .}} +{{end}} + +{{define "getFunc"}} +func New{{ CamelCase .FullName }}() *{{ CamelCase .FullName }} { + return &{{ CamelCase .FullName }}{ + {{ range $i, $v := (MakeIterable .Fields.Len) -}} + {{ $field := $.Fields.Get $i -}} + {{ if and (eq $field.Kind 11) (ne $field.Cardinality 3) -}} {{/* protoreflect.MessageKind protoreflect.Repeated */ -}} + {{ CamelCaseN $field.Name }}: New{{ CamelCase $field.Message.FullName }}(), + {{end -}} + {{end -}} + } +} +{{end}} + +{{define "error"}} +func (x *{{CamelCase .FullName}}) Error(p *packet.Packet, err error) { + packet.Encoder(p).Error(err) +} +{{end}} \ No newline at end of file From a4cfc713da93f802b76d269442f03b752423e9a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20S=C3=B8rlie=20Glomsaas?= Date: Thu, 14 Apr 2022 11:22:48 -0400 Subject: [PATCH 2/9] Fixing lint --- protoc-gen-frisbee/pkg/generator/generator.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/protoc-gen-frisbee/pkg/generator/generator.go b/protoc-gen-frisbee/pkg/generator/generator.go index 488f011..c6163a7 100644 --- a/protoc-gen-frisbee/pkg/generator/generator.go +++ b/protoc-gen-frisbee/pkg/generator/generator.go @@ -84,7 +84,7 @@ func (g *Generator) Generate(req *pluginpb.CodeGeneratorRequest) (res *pluginpb. err = temp.ExecuteTemplate(genFile, "base.go.txt", map[string]interface{}{ "pluginVersion": version.Version, "sourcePath": f.Desc.Path(), - "package": f.GoPackageName, + "package": packageName, "imports": requiredImports, "enums": f.Desc.Enums(), "messages": f.Desc.Messages(), From b69b878e61d33f96664a64aba10a1a944aaf356d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20S=C3=B8rlie=20Glomsaas?= Date: Thu, 14 Apr 2022 12:49:30 -0400 Subject: [PATCH 3/9] Correct function names --- protoc-gen-frisbee/internal/utils/utils.go | 6 +-- protoc-gen-frisbee/pkg/generator/generator.go | 32 +++++++------- protoc-gen-frisbee/templates/client.go.txt | 42 +++++++++---------- protoc-gen-frisbee/templates/decode.go.txt | 30 ++++++------- protoc-gen-frisbee/templates/decodeMap.go.txt | 6 +-- protoc-gen-frisbee/templates/encode.go.txt | 10 ++--- .../templates/interfaces.go.txt | 4 +- protoc-gen-frisbee/templates/server.go.txt | 4 +- protoc-gen-frisbee/templates/structs.go.txt | 4 +- 9 files changed, 69 insertions(+), 69 deletions(-) diff --git a/protoc-gen-frisbee/internal/utils/utils.go b/protoc-gen-frisbee/internal/utils/utils.go index f8f1f9c..9dc9760 100644 --- a/protoc-gen-frisbee/internal/utils/utils.go +++ b/protoc-gen-frisbee/internal/utils/utils.go @@ -71,11 +71,11 @@ func CamelCase(s string) string { return string(t) } -func CamelCaseFN(name protoreflect.FullName) string { +func CamelCaseFullName(name protoreflect.FullName) string { return CamelCase(string(name)) } -func CamelCaseN(name protoreflect.Name) string { +func CamelCaseName(name protoreflect.Name) string { return CamelCase(string(name)) } @@ -96,7 +96,7 @@ func FirstLowerCase(s string) string { return string(unicode.ToLower(r)) + s[n:] } -func FirstLowerCaseN(name protoreflect.Name) string { +func FirstLowerCaseName(name protoreflect.Name) string { return FirstLowerCase(string(name)) } diff --git a/protoc-gen-frisbee/pkg/generator/generator.go b/protoc-gen-frisbee/pkg/generator/generator.go index c6163a7..107f9d8 100644 --- a/protoc-gen-frisbee/pkg/generator/generator.go +++ b/protoc-gen-frisbee/pkg/generator/generator.go @@ -53,21 +53,21 @@ func (g *Generator) Generate(req *pluginpb.CodeGeneratorRequest) (res *pluginpb. return nil, err } - temp := template.Must(template.New("main").Funcs(template.FuncMap{ - "CamelCase": utils.CamelCaseFN, - "CamelCaseN": utils.CamelCaseN, - "MakeIterable": utils.MakeIterable, - "Counter": utils.Counter, - "FirstLowerCase": utils.FirstLowerCase, - "FirstLowerCaseN": utils.FirstLowerCaseN, - "FindValue": findValue, - "GetKind": getKind, - "GetLUTEncoder": getLUTEncoder, - "GetLUTDecoder": getLUTDecoder, - "GetEncodingFields": getEncodingFields, - "GetDecodingFields": getDecodingFields, - "GetKindLUT": getKindLUT, - "GetServerFields": getServerFields, + templ := template.Must(template.New("main").Funcs(template.FuncMap{ + "CamelCase": utils.CamelCaseFullName, + "CamelCaseName": utils.CamelCaseName, + "MakeIterable": utils.MakeIterable, + "Counter": utils.Counter, + "FirstLowerCase": utils.FirstLowerCase, + "FirstLowerCaseName": utils.FirstLowerCaseName, + "FindValue": findValue, + "GetKind": getKind, + "GetLUTEncoder": getLUTEncoder, + "GetLUTDecoder": getLUTDecoder, + "GetEncodingFields": getEncodingFields, + "GetDecodingFields": getDecodingFields, + "GetKindLUT": getKindLUT, + "GetServerFields": getServerFields, }).ParseGlob("protoc-gen-frisbee/templates/*")) for _, f := range plugin.Files { @@ -81,7 +81,7 @@ func (g *Generator) Generate(req *pluginpb.CodeGeneratorRequest) (res *pluginpb. packageName = string(f.GoPackageName) } - err = temp.ExecuteTemplate(genFile, "base.go.txt", map[string]interface{}{ + err = templ.ExecuteTemplate(genFile, "base.go.txt", map[string]interface{}{ "pluginVersion": version.Version, "sourcePath": f.Desc.Path(), "package": packageName, diff --git a/protoc-gen-frisbee/templates/client.go.txt b/protoc-gen-frisbee/templates/client.go.txt index 7da2b50..a8e65c8 100644 --- a/protoc-gen-frisbee/templates/client.go.txt +++ b/protoc-gen-frisbee/templates/client.go.txt @@ -5,9 +5,9 @@ type Client struct { {{ $service := $.services.Get $i -}} {{ range $i, $v := (MakeIterable $service.Methods.Len) -}} {{ $method := $service.Methods.Get $i -}} - next{{ CamelCaseN $method.Name }} atomic.Value - inflight{{ CamelCaseN $method.Name }}Mu sync.RWMutex - inflight{{ CamelCaseN $method.Name }} map[uint16]chan *{{ CamelCase $method.Output.FullName }} + next{{ CamelCaseName $method.Name }} atomic.Value + inflight{{ CamelCaseName $method.Name }}Mu sync.RWMutex + inflight{{ CamelCaseName $method.Name }} map[uint16]chan *{{ CamelCase $method.Output.FullName }} {{end -}} {{end -}} } @@ -34,8 +34,8 @@ func NewClient (tlsConfig *tls.Config, logger *zerolog.Logger) (*Client, error) {{ $service := $.services.Get $i -}} {{ range $i, $v := (MakeIterable $service.Methods.Len) -}} {{ $method := $service.Methods.Get $i -}} - c.next{{ CamelCaseN $method.Name }}.Store(uint16(0)) - c.inflight{{ CamelCaseN $method.Name }} = make(map[uint16]chan *{{ CamelCase $method.Output.FullName }}) + c.next{{ CamelCaseName $method.Name }}.Store(uint16(0)) + c.inflight{{ CamelCaseName $method.Name }} = make(map[uint16]chan *{{ CamelCase $method.Output.FullName }}) {{end -}} {{end -}} return c, nil @@ -52,14 +52,14 @@ func NewClient (tlsConfig *tls.Config, logger *zerolog.Logger) (*Client, error) {{ $method := $service.Methods.Get $i -}} {{ $count := call $counter -}} table[{{ $count }}] = func(ctx context.Context, incoming *packet.Packet) (outgoing *packet.Packet, action frisbee.Action) { - c.inflight{{ CamelCaseN $method.Name }}Mu.RLock() - if ch, ok := c.inflight{{ CamelCaseN $method.Name }}[incoming.Metadata.Id]; ok { - c.inflight{{ CamelCaseN $method.Name }}Mu.RUnlock() + c.inflight{{ CamelCaseName $method.Name }}Mu.RLock() + if ch, ok := c.inflight{{ CamelCaseName $method.Name }}[incoming.Metadata.Id]; ok { + c.inflight{{ CamelCaseName $method.Name }}Mu.RUnlock() res := New{{ CamelCase $method.Output.FullName }}() res.Decode(incoming) ch <- res } else { - c.inflight{{ CamelCaseN $method.Name }}Mu.RUnlock() + c.inflight{{ CamelCaseName $method.Name }}Mu.RUnlock() } return } @@ -74,20 +74,20 @@ func NewClient (tlsConfig *tls.Config, logger *zerolog.Logger) (*Client, error) {{ range $i, $v := (MakeIterable $service.Methods.Len) }} {{ $method := $service.Methods.Get $i -}} {{ $opIndex := call $counter -}} - func (c *Client) {{ CamelCaseN $method.Name }}(ctx context.Context, req *{{ CamelCase $method.Input.FullName }}) (res *{{ CamelCase $method.Output.FullName }}, err error) { + func (c *Client) {{ CamelCaseName $method.Name }}(ctx context.Context, req *{{ CamelCase $method.Input.FullName }}) (res *{{ CamelCase $method.Output.FullName }}, err error) { ch := make(chan *{{ CamelCase $method.Output.FullName }}, 1) p := packet.Get() p.Metadata.Operation = {{ $opIndex }} LOOP: - p.Metadata.Id = c.next{{ CamelCaseN $method.Name }}.Load().(uint16) - if !c.next{{ CamelCaseN $method.Name }}.CompareAndSwap(p.Metadata.Id, p.Metadata.Id+1) { + p.Metadata.Id = c.next{{ CamelCaseName $method.Name }}.Load().(uint16) + if !c.next{{ CamelCaseName $method.Name }}.CompareAndSwap(p.Metadata.Id, p.Metadata.Id+1) { goto LOOP } req.Encode(p) p.Metadata.ContentLength = uint32(len(p.Content.B)) - c.inflight{{ CamelCaseN $method.Name }}Mu.Lock() - c.inflight{{ CamelCaseN $method.Name }}[p.Metadata.Id] = ch - c.inflight{{ CamelCaseN $method.Name }}Mu.Unlock() + c.inflight{{ CamelCaseName $method.Name }}Mu.Lock() + c.inflight{{ CamelCaseName $method.Name }}[p.Metadata.Id] = ch + c.inflight{{ CamelCaseName $method.Name }}Mu.Unlock() err = c.Client.WritePacket(p) if err != nil { packet.Put(p) @@ -99,19 +99,19 @@ func NewClient (tlsConfig *tls.Config, logger *zerolog.Logger) (*Client, error) case <- ctx.Done(): err = ctx.Err() } - c.inflight{{ CamelCaseN $method.Name }}Mu.Lock() - delete(c.inflight{{ CamelCaseN $method.Name }}, p.Metadata.Id) - c.inflight{{ CamelCaseN $method.Name }}Mu.Unlock() + c.inflight{{ CamelCaseName $method.Name }}Mu.Lock() + delete(c.inflight{{ CamelCaseName $method.Name }}, p.Metadata.Id) + c.inflight{{ CamelCaseName $method.Name }}Mu.Unlock() packet.Put(p) return } - func (c *Client) {{ CamelCaseN $method.Name }}Ignore(ctx context.Context, req *{{ CamelCase $method.Input.FullName }}) (err error) { + func (c *Client) {{ CamelCaseName $method.Name }}Ignore(ctx context.Context, req *{{ CamelCase $method.Input.FullName }}) (err error) { p := packet.Get() p.Metadata.Operation = {{ $opIndex }} LOOP: - p.Metadata.Id = c.next{{ CamelCaseN $method.Name }}.Load().(uint16) - if !c.next{{ CamelCaseN $method.Name }}.CompareAndSwap(p.Metadata.Id, p.Metadata.Id+1) { + p.Metadata.Id = c.next{{ CamelCaseName $method.Name }}.Load().(uint16) + if !c.next{{ CamelCaseName $method.Name }}.CompareAndSwap(p.Metadata.Id, p.Metadata.Id+1) { goto LOOP } req.ignore = true diff --git a/protoc-gen-frisbee/templates/decode.go.txt b/protoc-gen-frisbee/templates/decode.go.txt index 53d2fef..6482f22 100644 --- a/protoc-gen-frisbee/templates/decode.go.txt +++ b/protoc-gen-frisbee/templates/decode.go.txt @@ -24,13 +24,13 @@ func (x *{{CamelCase .FullName}}) decode(d *packet.Decoder) error { {{ range $field := $decoding.Other -}} {{ $decoder := GetLUTDecoder $field.Kind -}} {{ if eq $field.Kind 12 -}} {{/* protoreflect.BytesKind */ -}} - x.{{ CamelCaseN $field.Name }}, err = d{{ $decoder }}(nil) + x.{{ CamelCaseName $field.Name }}, err = d{{ $decoder }}(nil) {{ else if eq $field.Kind 14 -}} {{/* protoreflect.EnumKind */ -}} - var {{ CamelCaseN $field.Name }}Temp uint32 - {{ CamelCaseN $field.Name }}Temp, err = d{{ $decoder }}() - x.{{ CamelCaseN $field.Name }} = {{ FindValue $field }}({{ CamelCaseN $field.Name }}Temp) + var {{ CamelCaseName $field.Name }}Temp uint32 + {{ CamelCaseName $field.Name }}Temp, err = d{{ $decoder }}() + x.{{ CamelCaseName $field.Name }} = {{ FindValue $field }}({{ CamelCaseName $field.Name }}Temp) {{ else -}} - x.{{ CamelCaseN $field.Name }}, err = d{{ $decoder }}() + x.{{ CamelCaseName $field.Name }}, err = d{{ $decoder }}() {{end -}} if err != nil { return err @@ -46,15 +46,15 @@ func (x *{{CamelCase .FullName}}) decode(d *packet.Decoder) error { if err != nil { return err } - if uint32(len(x.{{ CamelCaseN $field.Name }})) != sliceSize { - x.{{ CamelCaseN $field.Name }} = make({{ FindValue $field }}, sliceSize) + if uint32(len(x.{{ CamelCaseName $field.Name }})) != sliceSize { + x.{{ CamelCaseName $field.Name }} = make({{ FindValue $field }}, sliceSize) } for i := uint32(0); i < sliceSize; i++ { {{ $decoder := GetLUTDecoder $field.Kind -}} {{ if eq $field.Kind 11 -}} {{/* protoreflect.MessageKind */ -}} - err = x.{{ CamelCaseN $field.Name }}[i].decode(d) + err = x.{{ CamelCaseName $field.Name }}[i].decode(d) {{ else -}} - x.{{ CamelCaseN $field.Name }}[i], err = d{{ $decoder }}() + x.{{ CamelCaseName $field.Name }}[i], err = d{{ $decoder }}() {{end -}} if err != nil { return err @@ -67,21 +67,21 @@ func (x *{{CamelCase .FullName}}) decode(d *packet.Decoder) error { {{ $keyKind := GetKind $field.MapKey.Kind -}} {{ $valKind := GetKind $field.MapValue.Kind -}} - {{ CamelCaseN $field.Name }}Size, err := d.Map({{ $keyKind }}, {{ $valKind }}) + {{ CamelCaseName $field.Name }}Size, err := d.Map({{ $keyKind }}, {{ $valKind }}) if err != nil { return err } - x.{{ CamelCaseN $field.Name }} = New{{ CamelCase $field.FullName }}Map({{ CamelCaseN $field.Name }}Size) - err = x.{{ CamelCaseN $field.Name }}.decode(d, {{ CamelCaseN $field.Name }}Size) + x.{{ CamelCaseName $field.Name }} = New{{ CamelCase $field.FullName }}Map({{ CamelCaseName $field.Name }}Size) + err = x.{{ CamelCaseName $field.Name }}.decode(d, {{ CamelCaseName $field.Name }}Size) if err != nil { return err } } {{ else -}} - if x.{{ CamelCaseN $field.Name }} == nil { - x.{{ CamelCaseN $field.Name }} = New{{ CamelCase $field.Message.FullName }}() + if x.{{ CamelCaseName $field.Name }} == nil { + x.{{ CamelCaseName $field.Name }} = New{{ CamelCase $field.Message.FullName }}() } - err = x.{{ CamelCaseN $field.Name }}.decode(d) + err = x.{{ CamelCaseName $field.Name }}.decode(d) if err != nil { return err } diff --git a/protoc-gen-frisbee/templates/decodeMap.go.txt b/protoc-gen-frisbee/templates/decodeMap.go.txt index 64f143a..2cb0dfe 100644 --- a/protoc-gen-frisbee/templates/decodeMap.go.txt +++ b/protoc-gen-frisbee/templates/decodeMap.go.txt @@ -9,7 +9,7 @@ func (x {{CamelCase .FullName}}Map) decode(d *packet.Decoder, size uint32) error {{end -}} var v {{ FindValue .MapValue }} {{ if eq .MapValue.Kind 14 -}} {{/* protoreflect.EnumKind */ -}} - var {{ CamelCaseN .MapValue.Name }}Temp uint32 + var {{ CamelCaseName .MapValue.Name }}Temp uint32 {{end -}} var err error for i := uint32(0); i < size; i++ { @@ -34,8 +34,8 @@ func (x {{CamelCase .FullName}}Map) decode(d *packet.Decoder, size uint32) error err = v.decode(d) {{else -}} {{ if eq .MapValue.Kind 14 -}} {{/* protoreflect.EnumKind */ -}} - {{CamelCaseN .MapValue.Name}}Temp, err = d{{$valDecoder}}() - v = {{ FindValue .MapValue }}({{ CamelCaseN .MapValue.Name }}Temp) + {{CamelCaseName .MapValue.Name}}Temp, err = d{{$valDecoder}}() + v = {{ FindValue .MapValue }}({{ CamelCaseName .MapValue.Name }}Temp) {{else -}} v, err = d{{$valDecoder}}() {{end -}} diff --git a/protoc-gen-frisbee/templates/encode.go.txt b/protoc-gen-frisbee/templates/encode.go.txt index 4e92c72..4021ed6 100644 --- a/protoc-gen-frisbee/templates/encode.go.txt +++ b/protoc-gen-frisbee/templates/encode.go.txt @@ -21,13 +21,13 @@ func (x *{{ CamelCase .FullName }}) Encode (p *packet.Packet) { {{ range $field := .SliceFields -}} {{ $encoder := GetLUTEncoder $field.Kind -}} {{ if and (eq $encoder "") (eq $field.Kind 11) -}} {{/* protoreflect.MessageKind */ -}} - packet.Encoder(p).Slice(uint32(len(x.{{ CamelCaseN $field.Name }})), packet.AnyKind) - for _, v := range x.{{CamelCaseN $field.Name}} { + packet.Encoder(p).Slice(uint32(len(x.{{ CamelCaseName $field.Name }})), packet.AnyKind) + for _, v := range x.{{CamelCaseName $field.Name}} { v.Encode(p) } {{else -}} - packet.Encoder(p).Slice(uint32(len(x.{{ CamelCaseN $field.Name }})), {{ GetKindLUT $field.Kind }}) - for _, v := range x.{{ CamelCaseN $field.Name }} { + packet.Encoder(p).Slice(uint32(len(x.{{ CamelCaseName $field.Name }})), {{ GetKindLUT $field.Kind }}) + for _, v := range x.{{ CamelCaseName $field.Name }} { packet.Encoder(p){{$encoder}}(v) } {{end -}} @@ -36,6 +36,6 @@ func (x *{{ CamelCase .FullName }}) Encode (p *packet.Packet) { {{define "encodeMessages"}} {{ range $field := .MessageFields -}} - x.{{ CamelCaseN $field.Name }}.Encode(p) + x.{{ CamelCaseName $field.Name }}.Encode(p) {{end -}} {{end}} \ No newline at end of file diff --git a/protoc-gen-frisbee/templates/interfaces.go.txt b/protoc-gen-frisbee/templates/interfaces.go.txt index c3f8f87..2194c80 100644 --- a/protoc-gen-frisbee/templates/interfaces.go.txt +++ b/protoc-gen-frisbee/templates/interfaces.go.txt @@ -7,10 +7,10 @@ {{define "interface"}} -type {{ CamelCaseN .Name }} interface { +type {{ CamelCaseName .Name }} interface { {{ range $i, $v := MakeIterable .Methods.Len -}} {{ $method := $.Methods.Get $i -}} - {{ CamelCaseN $method.Name }} (context.Context, *{{ CamelCase $method.Input.FullName }}) (*{{ CamelCase $method.Output.FullName }}, error) + {{ CamelCaseName $method.Name }} (context.Context, *{{ CamelCase $method.Input.FullName }}) (*{{ CamelCase $method.Output.FullName }}, error) {{ end -}} } {{end}} \ No newline at end of file diff --git a/protoc-gen-frisbee/templates/server.go.txt b/protoc-gen-frisbee/templates/server.go.txt index 19b6257..72aafc1 100644 --- a/protoc-gen-frisbee/templates/server.go.txt +++ b/protoc-gen-frisbee/templates/server.go.txt @@ -36,12 +36,12 @@ type Server struct { err := req.Decode(incoming) if err == nil { if req.ignore { - {{ FirstLowerCaseN $service.Name }}.{{ CamelCaseN $method.Name }}(ctx, req) + {{ FirstLowerCaseName $service.Name }}.{{ CamelCaseName $method.Name }}(ctx, req) } else { var res *{{ CamelCase $method.Output.FullName }} outgoing = incoming outgoing.Content.Reset() - res, err = {{ FirstLowerCase (CamelCaseN $service.Name) }}.{{ CamelCaseN $method.Name }}(ctx, req) + res, err = {{ FirstLowerCase (CamelCaseName $service.Name) }}.{{ CamelCaseName $method.Name }}(ctx, req) if err != nil { res.Error(outgoing, err) } else { diff --git a/protoc-gen-frisbee/templates/structs.go.txt b/protoc-gen-frisbee/templates/structs.go.txt index b796b01..d758d61 100644 --- a/protoc-gen-frisbee/templates/structs.go.txt +++ b/protoc-gen-frisbee/templates/structs.go.txt @@ -26,7 +26,7 @@ {{ range $i, $v := (MakeIterable $.Fields.Len) -}} {{ $field := $.Fields.Get $i -}} {{ $value := FindValue $field -}} - {{ CamelCaseN $field.Name }} {{ $value }} + {{ CamelCaseName $field.Name }} {{ $value }} {{end -}} } @@ -43,7 +43,7 @@ func New{{ CamelCase .FullName }}() *{{ CamelCase .FullName }} { {{ range $i, $v := (MakeIterable .Fields.Len) -}} {{ $field := $.Fields.Get $i -}} {{ if and (eq $field.Kind 11) (ne $field.Cardinality 3) -}} {{/* protoreflect.MessageKind protoreflect.Repeated */ -}} - {{ CamelCaseN $field.Name }}: New{{ CamelCase $field.Message.FullName }}(), + {{ CamelCaseName $field.Name }}: New{{ CamelCase $field.Message.FullName }}(), {{end -}} {{end -}} } From ca87cda1244a8a918e96a02e50fb46003f9180ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20S=C3=B8rlie=20Glomsaas?= Date: Thu, 14 Apr 2022 12:53:02 -0400 Subject: [PATCH 4/9] Fix template file extensions --- protoc-gen-frisbee/pkg/generator/generator.go | 2 +- protoc-gen-frisbee/templates/{base.go.txt => base.templ} | 0 protoc-gen-frisbee/templates/{client.go.txt => client.templ} | 0 protoc-gen-frisbee/templates/{decode.go.txt => decode.templ} | 0 .../templates/{decodeMap.go.txt => decodeMap.templ} | 0 protoc-gen-frisbee/templates/{encode.go.txt => encode.templ} | 0 .../templates/{encodeMap.go.txt => encodeMap.templ} | 0 protoc-gen-frisbee/templates/{enums.go.txt => enums.templ} | 0 protoc-gen-frisbee/templates/{headers.go.txt => headers.templ} | 0 protoc-gen-frisbee/templates/{imports.go.txt => imports.templ} | 0 .../templates/{interfaces.go.txt => interfaces.templ} | 0 .../templates/{messages.go.txt => messages.templ} | 0 protoc-gen-frisbee/templates/{server.go.txt => server.templ} | 0 protoc-gen-frisbee/templates/{structs.go.txt => structs.templ} | 0 14 files changed, 1 insertion(+), 1 deletion(-) rename protoc-gen-frisbee/templates/{base.go.txt => base.templ} (100%) rename protoc-gen-frisbee/templates/{client.go.txt => client.templ} (100%) rename protoc-gen-frisbee/templates/{decode.go.txt => decode.templ} (100%) rename protoc-gen-frisbee/templates/{decodeMap.go.txt => decodeMap.templ} (100%) rename protoc-gen-frisbee/templates/{encode.go.txt => encode.templ} (100%) rename protoc-gen-frisbee/templates/{encodeMap.go.txt => encodeMap.templ} (100%) rename protoc-gen-frisbee/templates/{enums.go.txt => enums.templ} (100%) rename protoc-gen-frisbee/templates/{headers.go.txt => headers.templ} (100%) rename protoc-gen-frisbee/templates/{imports.go.txt => imports.templ} (100%) rename protoc-gen-frisbee/templates/{interfaces.go.txt => interfaces.templ} (100%) rename protoc-gen-frisbee/templates/{messages.go.txt => messages.templ} (100%) rename protoc-gen-frisbee/templates/{server.go.txt => server.templ} (100%) rename protoc-gen-frisbee/templates/{structs.go.txt => structs.templ} (100%) diff --git a/protoc-gen-frisbee/pkg/generator/generator.go b/protoc-gen-frisbee/pkg/generator/generator.go index 107f9d8..f348698 100644 --- a/protoc-gen-frisbee/pkg/generator/generator.go +++ b/protoc-gen-frisbee/pkg/generator/generator.go @@ -81,7 +81,7 @@ func (g *Generator) Generate(req *pluginpb.CodeGeneratorRequest) (res *pluginpb. packageName = string(f.GoPackageName) } - err = templ.ExecuteTemplate(genFile, "base.go.txt", map[string]interface{}{ + err = templ.ExecuteTemplate(genFile, "base.templ", map[string]interface{}{ "pluginVersion": version.Version, "sourcePath": f.Desc.Path(), "package": packageName, diff --git a/protoc-gen-frisbee/templates/base.go.txt b/protoc-gen-frisbee/templates/base.templ similarity index 100% rename from protoc-gen-frisbee/templates/base.go.txt rename to protoc-gen-frisbee/templates/base.templ diff --git a/protoc-gen-frisbee/templates/client.go.txt b/protoc-gen-frisbee/templates/client.templ similarity index 100% rename from protoc-gen-frisbee/templates/client.go.txt rename to protoc-gen-frisbee/templates/client.templ diff --git a/protoc-gen-frisbee/templates/decode.go.txt b/protoc-gen-frisbee/templates/decode.templ similarity index 100% rename from protoc-gen-frisbee/templates/decode.go.txt rename to protoc-gen-frisbee/templates/decode.templ diff --git a/protoc-gen-frisbee/templates/decodeMap.go.txt b/protoc-gen-frisbee/templates/decodeMap.templ similarity index 100% rename from protoc-gen-frisbee/templates/decodeMap.go.txt rename to protoc-gen-frisbee/templates/decodeMap.templ diff --git a/protoc-gen-frisbee/templates/encode.go.txt b/protoc-gen-frisbee/templates/encode.templ similarity index 100% rename from protoc-gen-frisbee/templates/encode.go.txt rename to protoc-gen-frisbee/templates/encode.templ diff --git a/protoc-gen-frisbee/templates/encodeMap.go.txt b/protoc-gen-frisbee/templates/encodeMap.templ similarity index 100% rename from protoc-gen-frisbee/templates/encodeMap.go.txt rename to protoc-gen-frisbee/templates/encodeMap.templ diff --git a/protoc-gen-frisbee/templates/enums.go.txt b/protoc-gen-frisbee/templates/enums.templ similarity index 100% rename from protoc-gen-frisbee/templates/enums.go.txt rename to protoc-gen-frisbee/templates/enums.templ diff --git a/protoc-gen-frisbee/templates/headers.go.txt b/protoc-gen-frisbee/templates/headers.templ similarity index 100% rename from protoc-gen-frisbee/templates/headers.go.txt rename to protoc-gen-frisbee/templates/headers.templ diff --git a/protoc-gen-frisbee/templates/imports.go.txt b/protoc-gen-frisbee/templates/imports.templ similarity index 100% rename from protoc-gen-frisbee/templates/imports.go.txt rename to protoc-gen-frisbee/templates/imports.templ diff --git a/protoc-gen-frisbee/templates/interfaces.go.txt b/protoc-gen-frisbee/templates/interfaces.templ similarity index 100% rename from protoc-gen-frisbee/templates/interfaces.go.txt rename to protoc-gen-frisbee/templates/interfaces.templ diff --git a/protoc-gen-frisbee/templates/messages.go.txt b/protoc-gen-frisbee/templates/messages.templ similarity index 100% rename from protoc-gen-frisbee/templates/messages.go.txt rename to protoc-gen-frisbee/templates/messages.templ diff --git a/protoc-gen-frisbee/templates/server.go.txt b/protoc-gen-frisbee/templates/server.templ similarity index 100% rename from protoc-gen-frisbee/templates/server.go.txt rename to protoc-gen-frisbee/templates/server.templ diff --git a/protoc-gen-frisbee/templates/structs.go.txt b/protoc-gen-frisbee/templates/structs.templ similarity index 100% rename from protoc-gen-frisbee/templates/structs.go.txt rename to protoc-gen-frisbee/templates/structs.templ From e7d8c7f5f30f85b3ee50ea96f945ca71f707345d Mon Sep 17 00:00:00 2001 From: Shivansh Vij Date: Wed, 20 Apr 2022 18:14:55 -0400 Subject: [PATCH 5/9] Updating decoder to only require a byte slice, not a packet.Packet (#92) Also upgrading trunk linter version --- .github/workflows/lint.yml | 2 +- .trunk/trunk.yaml | 2 +- pkg/packet/decoder.go | 14 ++---- pkg/packet/decoder_test.go | 60 +++++++++++------------ pkg/packet/packet_test.go | 8 +-- protoc-gen-frisbee/templates/decode.templ | 2 +- 6 files changed, 42 insertions(+), 46 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index cd09161..a38f10e 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -19,4 +19,4 @@ jobs: key: trunk-${{ runner.os }} - name: Trunk Check - uses: trunk-io/trunk-action@v0.4.0-beta + uses: trunk-io/trunk-action@v1.0.0 diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 088f9d1..9f4ada4 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -1,6 +1,6 @@ version: 0.1 cli: - version: 0.8.1-beta + version: 0.10.0-beta lint: enabled: - gitleaks@7.6.1 diff --git a/pkg/packet/decoder.go b/pkg/packet/decoder.go index ea8a435..91a0b8e 100644 --- a/pkg/packet/decoder.go +++ b/pkg/packet/decoder.go @@ -23,35 +23,31 @@ import ( var decoderPool sync.Pool type Decoder struct { - p *Packet b []byte } -func GetDecoder(p *Packet) (d *Decoder) { +func GetDecoder(b []byte) (d *Decoder) { v := decoderPool.Get() if v == nil { d = &Decoder{ - p: p, - b: p.Content.B, + b: b, } } else { d = v.(*Decoder) - d.p = p - d.b = p.Content.B + d.b = b } return } -func Return(d *Decoder) { +func ReturnDecoder(d *Decoder) { if d != nil { - d.p = nil d.b = nil decoderPool.Put(d) } } func (d *Decoder) Return() { - Return(d) + ReturnDecoder(d) } func (d *Decoder) Nil() (value bool) { diff --git a/pkg/packet/decoder_test.go b/pkg/packet/decoder_test.go index 266e1d3..98d2818 100644 --- a/pkg/packet/decoder_test.go +++ b/pkg/packet/decoder_test.go @@ -28,7 +28,7 @@ func TestDecoderNil(t *testing.T) { p := Get() Encoder(p).Nil() - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value := d.Nil() assert.True(t, value) @@ -40,7 +40,7 @@ func TestDecoderNil(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Nil() - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value = d.Nil() d.Return() p.Content.Reset() @@ -64,7 +64,7 @@ func TestDecoderMap(t *testing.T) { e.String(k).Uint32(v) } - d := GetDecoder(p) + d := GetDecoder(p.Content.B) size, err := d.Map(StringKind, Uint32Kind) assert.NoError(t, err) assert.Equal(t, uint32(len(m)), size) @@ -93,7 +93,7 @@ func TestDecoderMap(t *testing.T) { for k, v = range m { e.String(k).Uint32(v) } - d = GetDecoder(p) + d = GetDecoder(p.Content.B) size, err = d.Map(StringKind, Uint32Kind) for i := uint32(0); i < size; i++ { _, _ = d.String() @@ -118,7 +118,7 @@ func TestDecoderSlice(t *testing.T) { e.String(v) } - d := GetDecoder(p) + d := GetDecoder(p.Content.B) size, err := d.Slice(StringKind) assert.NoError(t, err) assert.Equal(t, uint32(len(m)), size) @@ -143,7 +143,7 @@ func TestDecoderSlice(t *testing.T) { for _, v := range m { e.String(v) } - d = GetDecoder(p) + d = GetDecoder(p.Content.B) size, err = d.Slice(StringKind) for i := uint32(0); i < size; i++ { _, _ = d.String() @@ -164,7 +164,7 @@ func TestDecoderBytes(t *testing.T) { Encoder(p).Bytes(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.Bytes(nil) assert.NoError(t, err) assert.Equal(t, v, value) @@ -177,7 +177,7 @@ func TestDecoderBytes(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Bytes(v) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.Bytes(value) d.Return() p.Content.Reset() @@ -195,7 +195,7 @@ func TestDecoderString(t *testing.T) { Encoder(p).String(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.String() assert.NoError(t, err) assert.Equal(t, v, value) @@ -208,7 +208,7 @@ func TestDecoderString(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).String(v) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.String() d.Return() p.Content.Reset() @@ -226,7 +226,7 @@ func TestDecoderError(t *testing.T) { Encoder(p).Error(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.Error() assert.NoError(t, err) assert.ErrorIs(t, value, v) @@ -239,7 +239,7 @@ func TestDecoderError(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Error(v) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.Error() d.Return() p.Content.Reset() @@ -255,7 +255,7 @@ func TestDecoderBool(t *testing.T) { p := Get() Encoder(p).Bool(true) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.Bool() assert.NoError(t, err) assert.True(t, value) @@ -268,7 +268,7 @@ func TestDecoderBool(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Bool(true) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.Bool() d.Return() p.Content.Reset() @@ -286,7 +286,7 @@ func TestDecoderUint8(t *testing.T) { Encoder(p).Uint8(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.Uint8() assert.NoError(t, err) assert.Equal(t, v, value) @@ -299,7 +299,7 @@ func TestDecoderUint8(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Uint8(v) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.Uint8() d.Return() p.Content.Reset() @@ -317,7 +317,7 @@ func TestDecoderUint16(t *testing.T) { Encoder(p).Uint16(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.Uint16() assert.NoError(t, err) assert.Equal(t, v, value) @@ -330,7 +330,7 @@ func TestDecoderUint16(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Uint16(v) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.Uint16() d.Return() p.Content.Reset() @@ -348,7 +348,7 @@ func TestDecoderUint32(t *testing.T) { Encoder(p).Uint32(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.Uint32() assert.NoError(t, err) assert.Equal(t, v, value) @@ -361,7 +361,7 @@ func TestDecoderUint32(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Uint32(v) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.Uint32() d.Return() p.Content.Reset() @@ -379,7 +379,7 @@ func TestDecoderUint64(t *testing.T) { Encoder(p).Uint64(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.Uint64() assert.NoError(t, err) assert.Equal(t, v, value) @@ -392,7 +392,7 @@ func TestDecoderUint64(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Uint64(v) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.Uint64() d.Return() p.Content.Reset() @@ -410,7 +410,7 @@ func TestDecoderInt32(t *testing.T) { Encoder(p).Int32(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.Int32() assert.NoError(t, err) assert.Equal(t, v, value) @@ -423,7 +423,7 @@ func TestDecoderInt32(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Int32(v) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.Int32() d.Return() p.Content.Reset() @@ -441,7 +441,7 @@ func TestDecoderInt64(t *testing.T) { Encoder(p).Int64(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.Int64() assert.NoError(t, err) assert.Equal(t, v, value) @@ -454,7 +454,7 @@ func TestDecoderInt64(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Int64(v) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.Int64() d.Return() p.Content.Reset() @@ -472,7 +472,7 @@ func TestDecoderFloat32(t *testing.T) { Encoder(p).Float32(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.Float32() assert.NoError(t, err) assert.Equal(t, v, value) @@ -485,7 +485,7 @@ func TestDecoderFloat32(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Float32(v) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.Float32() d.Return() p.Content.Reset() @@ -503,7 +503,7 @@ func TestDecoderFloat64(t *testing.T) { Encoder(p).Float64(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) value, err := d.Float64() assert.NoError(t, err) assert.Equal(t, v, value) @@ -516,7 +516,7 @@ func TestDecoderFloat64(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Float64(v) - d = GetDecoder(p) + d = GetDecoder(p.Content.B) value, err = d.Float64() d.Return() p.Content.Reset() diff --git a/pkg/packet/packet_test.go b/pkg/packet/packet_test.go index 2fa070f..ce55b86 100644 --- a/pkg/packet/packet_test.go +++ b/pkg/packet/packet_test.go @@ -302,7 +302,7 @@ func TestCompleteChain(t *testing.T) { val := new(testStruct) var err error - d := GetDecoder(p) + d := GetDecoder(p.Content.B) val.err, err = d.Error() assert.NoError(t, err) @@ -391,7 +391,7 @@ func TestCompleteChain(t *testing.T) { p.Content.Reset() n := testing.AllocsPerRun(100, func() { Encoder(p).Error(test.err).String(test.test).Bytes(test.b).Uint8(test.num1).Uint16(test.num2).Uint32(test.num3).Uint64(test.num4).Bool(test.truth).Nil() - d = GetDecoder(p) + d = GetDecoder(p.Content.B) val.err, err = d.Error() val.test, err = d.String() val.b, err = d.Bytes(val.b) @@ -413,7 +413,7 @@ func TestNilSlice(t *testing.T) { p := Get() Encoder(p).Slice(uint32(len(s)), StringKind) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) j, err := d.Slice(StringKind) assert.NoError(t, err) assert.Equal(t, uint32(len(s)), j) @@ -431,7 +431,7 @@ func TestError(t *testing.T) { p := Get() Encoder(p).Error(v) - d := GetDecoder(p) + d := GetDecoder(p.Content.B) _, err := d.String() assert.ErrorIs(t, err, InvalidString) diff --git a/protoc-gen-frisbee/templates/decode.templ b/protoc-gen-frisbee/templates/decode.templ index 6482f22..d70b273 100644 --- a/protoc-gen-frisbee/templates/decode.templ +++ b/protoc-gen-frisbee/templates/decode.templ @@ -3,7 +3,7 @@ func (x *{{ CamelCase .FullName }}) Decode (p *packet.Packet) error { if x == nil { return NilDecode } - d := packet.GetDecoder(p) + d := packet.GetDecoder(p.Content.B) return x.decode(d) } {{end}} From 566f3cccfe85eeb86cb2ecf12c6a19484102b9ce Mon Sep 17 00:00:00 2001 From: Shivansh Vij Date: Wed, 20 Apr 2022 18:18:44 -0400 Subject: [PATCH 6/9] Updating changelog --- CHANGELOG.md | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e5a4eba..dc666e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +## [v0.4.2] - 2022-04-20 (Beta) + +## Changes + +- Refactored the RPC Generator to use the `text/template` + package ([#90](https://github.com/loopholelabs/frisbee/pull/90)) +- Updated `pkg/packet.Decoder` to require only a `[]byte` to create a new decoder, instead of + a `*packet.Packet` ([#92](https://github.com/loopholelabs/frisbee/pull/92)) +- Updated Trunk Linter to v0.10.0-beta ([#92](https://github.com/loopholelabs/frisbee/pull/92)) + ## [v0.4.1] - 2022-03-24 (Beta) ## Changes @@ -209,16 +219,28 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Initial Release of Frisbee -[unreleased]: https://github.com/loopholelabs/frisbee/compare/v0.4.1...HEAD +[unreleased]: https://github.com/loopholelabs/frisbee/compare/v0.4.2...HEAD + +[v0.4.2]: https://github.com/loopholelabs/frisbee/compare/v0.4.1...v0.4.2 + [v0.4.1]: https://github.com/loopholelabs/frisbee/compare/v0.4.0...v0.4.1 + [v0.4.0]: https://github.com/loopholelabs/frisbee/compare/v0.3.2...v0.4.0 + [v0.3.2]: https://github.com/loopholelabs/frisbee/compare/v0.3.1...v0.3.2 + [v0.3.1]: https://github.com/loopholelabs/frisbee/compare/v0.3.0...v0.3.1 + [v0.3.0]: https://github.com/loopholelabs/frisbee/compare/v0.2.4...v0.3.0 + [v0.2.4]: https://github.com/loopholelabs/frisbee/compare/v0.2.3...v0.2.4 + [v0.2.3]: https://github.com/loopholelabs/frisbee/compare/v0.2.2...v0.2.3 + [v0.2.2]: https://github.com/loopholelabs/frisbee/compare/v0.2.1...v0.2.2 + [v0.2.1]: https://github.com/loopholelabs/frisbee/compare/v0.2.0...v0.2.1 + [v0.2.0]: https://github.com/loopholelabs/frisbee/compare/v0.1.6...v0.2.0 [v0.1.6]: https://github.com/loopholelabs/frisbee/compare/v0.1.5...v0.1.6 [v0.1.5]: https://github.com/loopholelabs/frisbee/compare/v0.1.4...v0.1.5 From da2f05ef00d254f58923bbd402a23f6777d971b9 Mon Sep 17 00:00:00 2001 From: Shivansh Vij Date: Wed, 20 Apr 2022 18:18:59 -0400 Subject: [PATCH 7/9] Fixing changelog linting --- CHANGELOG.md | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc666e9..b197b40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -220,27 +220,16 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Initial Release of Frisbee [unreleased]: https://github.com/loopholelabs/frisbee/compare/v0.4.2...HEAD - [v0.4.2]: https://github.com/loopholelabs/frisbee/compare/v0.4.1...v0.4.2 - [v0.4.1]: https://github.com/loopholelabs/frisbee/compare/v0.4.0...v0.4.1 - [v0.4.0]: https://github.com/loopholelabs/frisbee/compare/v0.3.2...v0.4.0 - [v0.3.2]: https://github.com/loopholelabs/frisbee/compare/v0.3.1...v0.3.2 - [v0.3.1]: https://github.com/loopholelabs/frisbee/compare/v0.3.0...v0.3.1 - [v0.3.0]: https://github.com/loopholelabs/frisbee/compare/v0.2.4...v0.3.0 - [v0.2.4]: https://github.com/loopholelabs/frisbee/compare/v0.2.3...v0.2.4 - [v0.2.3]: https://github.com/loopholelabs/frisbee/compare/v0.2.2...v0.2.3 - [v0.2.2]: https://github.com/loopholelabs/frisbee/compare/v0.2.1...v0.2.2 - [v0.2.1]: https://github.com/loopholelabs/frisbee/compare/v0.2.0...v0.2.1 - [v0.2.0]: https://github.com/loopholelabs/frisbee/compare/v0.1.6...v0.2.0 [v0.1.6]: https://github.com/loopholelabs/frisbee/compare/v0.1.5...v0.1.6 [v0.1.5]: https://github.com/loopholelabs/frisbee/compare/v0.1.4...v0.1.5 From 0fc296794411110a5d4d5a2c42f776f82f5e51df Mon Sep 17 00:00:00 2001 From: Shivansh Vij Date: Wed, 20 Apr 2022 18:21:09 -0400 Subject: [PATCH 8/9] updating maintainers --- MAINTAINERS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/MAINTAINERS.md b/MAINTAINERS.md index 6c79a6a..00ffd95 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -1,2 +1,3 @@ - Shivansh Vij @shivanshvij - Jonathan Sun @jspsun +- Alex Sørlie Glomsaas @supermanifolds From 0a968ca9902a13adb28977f753b7d2e1e78da9e8 Mon Sep 17 00:00:00 2001 From: Shivansh Vij Date: Wed, 20 Apr 2022 18:24:47 -0400 Subject: [PATCH 9/9] updating trunk linters --- .trunk/trunk.yaml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 9f4ada4..6e6ea48 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -3,8 +3,8 @@ cli: version: 0.10.0-beta lint: enabled: - - gitleaks@7.6.1 - - gofmt@1.17.6 - - golangci-lint@1.42.1 - - markdownlint@0.29.0 - - prettier@2.4.1 + - gitleaks@8.7.1 + - gofmt@1.18.1 + - golangci-lint@1.45.2 + - markdownlint@0.31.1 + - prettier@2.6.2