pax_global_header00006660000000000000000000000064133122577720014523gustar00rootroot0000000000000052 comment=b13d74d757bf9ea3e5574a491eb6646bdc4e2a04 yarpc-0.0.1/000077500000000000000000000000001331225777200126375ustar00rootroot00000000000000yarpc-0.0.1/.gitignore000066400000000000000000000000211331225777200146200ustar00rootroot00000000000000/protoc-gen-yarpcyarpc-0.0.1/Godeps000066400000000000000000000002071331225777200140020ustar00rootroot00000000000000github.com/gogo/protobuf 1c2b16bc280d6635de6c52fc1471ab962dc36ec9 github.com/influxdata/yamux e7f91523e648eeb91537e420aebbd96aa64ab6ae yarpc-0.0.1/LICENSE000066400000000000000000000020761331225777200136510ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2017-2018 InfluxData Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.yarpc-0.0.1/README.md000066400000000000000000000003431331225777200141160ustar00rootroot00000000000000yarpc ===== yarpc is Yet Another RPC package for Go. In a barely working state right now, little error handling and lots of details still to resolve. * How shall header and trailer data be handled (for open tracing, status)yarpc-0.0.1/call.go000066400000000000000000000020621331225777200141010ustar00rootroot00000000000000package yarpc import ( "context" "encoding/binary" "github.com/influxdata/yamux" ) func Invoke(ctx context.Context, api uint16, args interface{}, reply interface{}, cc *ClientConn) error { stream, err := cc.NewStream() if err != nil { // TODO(sgc): convert to RPC error return err } defer stream.Close() var tmp [2]byte binary.BigEndian.PutUint16(tmp[:], api) _, err = stream.Write(tmp[:]) if err != nil { return err } err = sendRequest(ctx, cc.dopts, stream, args) if err != nil { return err } err = recvResponse(ctx, cc.dopts, stream, reply) if err != nil { return err } return nil } func sendRequest(ctx context.Context, dopts dialOptions, stream *yamux.Stream, args interface{}) error { outBuf, err := encode(dopts.codec, args) if err != nil { return err } _, err = stream.Write(outBuf) return err } func recvResponse(ctx context.Context, dopts dialOptions, stream *yamux.Stream, reply interface{}) error { p := &parser{r: stream} err := decode(p, dopts.codec, stream, reply) if err != nil { return err } return nil } yarpc-0.0.1/call_test.go000066400000000000000000000000161331225777200151350ustar00rootroot00000000000000package yarpc yarpc-0.0.1/clientconn.go000066400000000000000000000021031331225777200153160ustar00rootroot00000000000000package yarpc import ( "net" "context" "github.com/influxdata/yamux" ) type dialOptions struct { codec Codec } type DialOption func(*dialOptions) func WithCodec(c Codec) DialOption { return func(o *dialOptions) { o.codec = c } } func Dial(addr string, opt ...DialOption) (*ClientConn, error) { return DialContext(context.Background(), addr, opt...) } func DialContext(ctx context.Context, addr string, opts ...DialOption) (*ClientConn, error) { cn, err := net.Dial("tcp", addr) if err != nil { return nil, err } s, err := yamux.Client(cn, nil) if err != nil { return nil, err } cc := &ClientConn{s: s} cc.ctx, cc.cancel = context.WithCancel(ctx) for _, opt := range opts { opt(&cc.dopts) } if cc.dopts.codec == nil { cc.dopts.codec = NewCodec() } return cc, nil } type ClientConn struct { ctx context.Context cancel context.CancelFunc s *yamux.Session dopts dialOptions } func (cc *ClientConn) NewStream() (*yamux.Stream, error) { return cc.s.OpenStream() } func (cc *ClientConn) Close() error { cc.cancel() return cc.s.Close() } yarpc-0.0.1/cmd/000077500000000000000000000000001331225777200134025ustar00rootroot00000000000000yarpc-0.0.1/cmd/protoc-gen-yarpc/000077500000000000000000000000001331225777200165735ustar00rootroot00000000000000yarpc-0.0.1/cmd/protoc-gen-yarpc/generator/000077500000000000000000000000001331225777200205615ustar00rootroot00000000000000yarpc-0.0.1/cmd/protoc-gen-yarpc/generator/generator.go000066400000000000000000001536121331225777200231060ustar00rootroot00000000000000// Protocol Buffers for Go with Gadgets // // Copyright (c) 2013, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* The code generator for the plugin for the Google protocol buffer compiler. It generates Go code from the protocol buffer description files read by the main routine. */ package generator import ( "bytes" "fmt" "log" "os" "path" "strconv" "strings" "unicode" "unicode/utf8" "github.com/gogo/protobuf/gogoproto" "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" plugin "github.com/gogo/protobuf/protoc-gen-gogo/plugin" ) // generatedCodeVersion indicates a version of the generated code. // It is incremented whenever an incompatibility between the generated code and // proto package is introduced; the generated code references // a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion). const generatedCodeVersion = 2 // A Plugin provides functionality to add to the output during Go code generation, // such as to produce RPC stubs. type Plugin interface { // Name identifies the plugin. Name() string // Init is called once after data structures are built but before // code generation begins. Init(g *Generator) // Generate produces the code generated by the plugin for this file, // except for the imports, by calling the generator's methods P, In, and Out. Generate(file *FileDescriptor) // GenerateImports produces the import declarations for this file. // It is called after Generate. GenerateImports(file *FileDescriptor) } // Each type we import as a protocol buffer (other than FileDescriptorProto) needs // a pointer to the FileDescriptorProto that represents it. These types achieve that // wrapping by placing each Proto inside a struct with the pointer to its File. The // structs have the same names as their contents, with "Proto" removed. // FileDescriptor is used to store the things that it points to. // The file and package name method are common to messages and enums. type common struct { file *descriptor.FileDescriptorProto // File this object comes from. } // PackageName is name in the package clause in the generated file. func (c *common) PackageName() string { return uniquePackageOf(c.file) } func (c *common) File() *descriptor.FileDescriptorProto { return c.file } func fileIsProto3(file *descriptor.FileDescriptorProto) bool { return file.GetSyntax() == "proto3" } func (c *common) proto3() bool { return fileIsProto3(c.file) } // Descriptor represents a protocol buffer message. type Descriptor struct { common *descriptor.DescriptorProto parent *Descriptor // The containing message, if any. nested []*Descriptor // Inner messages, if any. enums []*EnumDescriptor // Inner enums, if any. ext []*ExtensionDescriptor // Extensions, if any. typename []string // Cached typename vector. index int // The index into the container, whether the file or another message. path string // The SourceCodeInfo path as comma-separated integers. group bool } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (d *Descriptor) TypeName() []string { if d.typename != nil { return d.typename } n := 0 for parent := d; parent != nil; parent = parent.parent { n++ } s := make([]string, n, n) for parent := d; parent != nil; parent = parent.parent { n-- s[n] = parent.GetName() } d.typename = s return s } func (d *Descriptor) allowOneof() bool { return true } // EnumDescriptor describes an enum. If it's at top level, its parent will be nil. // Otherwise it will be the descriptor of the message in which it is defined. type EnumDescriptor struct { common *descriptor.EnumDescriptorProto parent *Descriptor // The containing message, if any. typename []string // Cached typename vector. index int // The index into the container, whether the file or a message. path string // The SourceCodeInfo path as comma-separated integers. } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (e *EnumDescriptor) TypeName() (s []string) { if e.typename != nil { return e.typename } name := e.GetName() if e.parent == nil { s = make([]string, 1) } else { pname := e.parent.TypeName() s = make([]string, len(pname)+1) copy(s, pname) } s[len(s)-1] = name e.typename = s return s } // alias provides the TypeName corrected for the application of any naming // extensions on the enum type. It should be used for generating references to // the Go types and for calculating prefixes. func (e *EnumDescriptor) alias() (s []string) { s = e.TypeName() if gogoproto.IsEnumCustomName(e.EnumDescriptorProto) { s[len(s)-1] = gogoproto.GetEnumCustomName(e.EnumDescriptorProto) } return } // Everything but the last element of the full type name, CamelCased. // The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... . func (e *EnumDescriptor) prefix() string { typeName := e.alias() if e.parent == nil { // If the enum is not part of a message, the prefix is just the type name. return CamelCase(typeName[len(typeName)-1]) + "_" } return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_" } // The integer value of the named constant in this enumerated type. func (e *EnumDescriptor) integerValueAsString(name string) string { for _, c := range e.Value { if c.GetName() == name { return fmt.Sprint(c.GetNumber()) } } log.Fatal("cannot find value for enum constant") return "" } // ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil. // Otherwise it will be the descriptor of the message in which it is defined. type ExtensionDescriptor struct { common *descriptor.FieldDescriptorProto parent *Descriptor // The containing message, if any. } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (e *ExtensionDescriptor) TypeName() (s []string) { name := e.GetName() if e.parent == nil { // top-level extension s = make([]string, 1) } else { pname := e.parent.TypeName() s = make([]string, len(pname)+1) copy(s, pname) } s[len(s)-1] = name return s } // DescName returns the variable name used for the generated descriptor. func (e *ExtensionDescriptor) DescName() string { // The full type name. typeName := e.TypeName() // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix. for i, s := range typeName { typeName[i] = CamelCase(s) } return "E_" + strings.Join(typeName, "_") } // ImportedDescriptor describes a type that has been publicly imported from another file. type ImportedDescriptor struct { common o Object } func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() } // FileDescriptor describes an protocol buffer descriptor file (.proto). // It includes slices of all the messages and enums defined within it. // Those slices are constructed by WrapTypes. type FileDescriptor struct { *descriptor.FileDescriptorProto desc []*Descriptor // All the messages defined in this file. enum []*EnumDescriptor // All the enums defined in this file. ext []*ExtensionDescriptor // All the top-level extensions defined in this file. imp []*ImportedDescriptor // All types defined in files publicly imported by this file. // Comments, stored as a map of path (comma-separated integers) to the comment. comments map[string]*descriptor.SourceCodeInfo_Location // The full list of symbols that are exported, // as a map from the exported object to its symbols. // This is used for supporting public imports. exported map[Object][]symbol index int // The index of this file in the list of files to generate code for proto3 bool // whether to generate proto3 code for this file suffix string // filename suffix } // PackageName is the package name we'll use in the generated code to refer to this file. func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) } // VarName is the variable name we'll use in the generated code to refer // to the compressed bytes of this descriptor. It is not exported, so // it is only valid inside the generated package. func (d *FileDescriptor) VarName() string { return fmt.Sprintf("fileDescriptor%v", FileName(d)) } // goPackageOption interprets the file's go_package option. // If there is no go_package, it returns ("", "", false). // If there's a simple name, it returns ("", pkg, true). // If the option implies an import path, it returns (impPath, pkg, true). func (d *FileDescriptor) goPackageOption() (impPath, pkg string, ok bool) { pkg = d.GetOptions().GetGoPackage() if pkg == "" { return } ok = true // The presence of a slash implies there's an import path. slash := strings.LastIndex(pkg, "/") if slash < 0 { return } impPath, pkg = pkg, pkg[slash+1:] // A semicolon-delimited suffix overrides the package name. sc := strings.IndexByte(impPath, ';') if sc < 0 { return } impPath, pkg = impPath[:sc], impPath[sc+1:] return } // goPackageName returns the Go package name to use in the // generated Go file. The result explicit reports whether the name // came from an option go_package statement. If explicit is false, // the name was derived from the protocol buffer's package statement // or the input file name. func (d *FileDescriptor) goPackageName() (name string, explicit bool) { // Does the file have a "go_package" option? if _, pkg, ok := d.goPackageOption(); ok { return pkg, true } // Does the file have a package clause? if pkg := d.GetPackage(); pkg != "" { return pkg, false } // Use the file base name. return baseName(d.GetName()), false } // goFileName returns the output name for the generated Go file. func (d *FileDescriptor) goFileName() string { name := *d.Name if ext := path.Ext(name); ext == ".proto" || ext == ".protodevel" { name = name[:len(name)-len(ext)] } name += d.suffix // Does the file have a "go_package" option? // If it does, it may override the filename. if impPath, _, ok := d.goPackageOption(); ok && impPath != "" { // Replace the existing dirname with the declared import path. _, name = path.Split(name) name = path.Join(impPath, name) return name } return name } func (d *FileDescriptor) addExport(obj Object, sym symbol) { d.exported[obj] = append(d.exported[obj], sym) } // symbol is an interface representing an exported Go symbol. type symbol interface { // GenerateAlias should generate an appropriate alias // for the symbol from the named package. GenerateAlias(g *Generator, pkg string) } // Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects. type Object interface { PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness. TypeName() []string File() *descriptor.FileDescriptorProto } // Each package name we generate must be unique. The package we're generating // gets its own name but every other package must have a unique name that does // not conflict in the code we generate. These names are chosen globally (although // they don't have to be, it simplifies things to do them globally). func uniquePackageOf(fd *descriptor.FileDescriptorProto) string { s, ok := uniquePackageName[fd] if !ok { log.Fatal("internal error: no package name defined for " + fd.GetName()) } return s } // Generator is the type whose methods generate the output, stored in the associated response structure. type Generator struct { *bytes.Buffer Request *plugin.CodeGeneratorRequest // The input. Response *plugin.CodeGeneratorResponse // The output. Suffix string // Filename suffix Param map[string]string // Command-line parameters. PackageImportPath string // Go import path of the package we're generating code for ImportPrefix string // String to prefix to imported package file names. ImportMap map[string]string // Mapping from .proto file name to import path Pkg map[string]string // The names under which we import support packages packageName string // What we're calling ourselves. allFiles []*FileDescriptor // All files in the tree allFilesByName map[string]*FileDescriptor // All files by filename. genFiles []*FileDescriptor // Those files we will generate output for. file *FileDescriptor // The file we are compiling now. usedPackages map[string]bool // Names of packages used in current file. typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax. init []string // Lines to emit in the init function. indent string writeOutput bool customImports []string writtenImports map[string]bool // For de-duplicating written imports } // New creates a new generator and allocates the request and response protobufs. func New() *Generator { g := new(Generator) g.Buffer = new(bytes.Buffer) g.Request = new(plugin.CodeGeneratorRequest) g.Response = new(plugin.CodeGeneratorResponse) g.Suffix = ".pb.go" g.writtenImports = make(map[string]bool) uniquePackageName = make(map[*descriptor.FileDescriptorProto]string) pkgNamesInUse = make(map[string][]*FileDescriptor) return g } // Error reports a problem, including an error, and exits the program. func (g *Generator) Error(err error, msgs ...string) { s := strings.Join(msgs, " ") + ":" + err.Error() log.Print("protoc-gen-yarpc: error:", s) os.Exit(1) } // Fail reports a problem and exits the program. func (g *Generator) Fail(msgs ...string) { s := strings.Join(msgs, " ") log.Print("protoc-gen-yarpc: error:", s) os.Exit(1) } // CommandLineParameters breaks the comma-separated list of key=value pairs // in the parameter (a member of the request protobuf) into a key/value map. // It then sets file name mappings defined by those entries. func (g *Generator) CommandLineParameters(parameter string) { g.Param = make(map[string]string) for _, p := range strings.Split(parameter, ",") { if i := strings.Index(p, "="); i < 0 { g.Param[p] = "" } else { g.Param[p[0:i]] = p[i+1:] } } g.ImportMap = make(map[string]string) for k, v := range g.Param { switch k { case "import_prefix": g.ImportPrefix = v case "import_path": g.PackageImportPath = v default: if len(k) > 0 && k[0] == 'M' { g.ImportMap[k[1:]] = v } } } } // DefaultPackageName returns the package name printed for the object. // If its file is in a different package, it returns the package name we're using for this file, plus ".". // Otherwise it returns the empty string. func (g *Generator) DefaultPackageName(obj Object) string { pkg := obj.PackageName() if pkg == g.packageName { return "" } return pkg + "." } // For each input file, the unique package name to use, underscored. var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string) // Package names already registered. Key is the name from the .proto file; // value is the name that appears in the generated code. var pkgNamesInUse = make(map[string][]*FileDescriptor) // Create and remember a guaranteed unique package name for this file descriptor. // Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and // has no file descriptor. func RegisterUniquePackageName(pkg string, f *FileDescriptor) string { // Convert dots to underscores before finding a unique alias. pkg = strings.Map(badToUnderscore, pkg) var i = -1 var ptr *FileDescriptor = nil for i, ptr = range pkgNamesInUse[pkg] { if ptr == f { if i == 0 { return pkg } return pkg + strconv.Itoa(i) } } pkgNamesInUse[pkg] = append(pkgNamesInUse[pkg], f) i += 1 if i > 0 { pkg = pkg + strconv.Itoa(i) } if f != nil { uniquePackageName[f.FileDescriptorProto] = pkg } return pkg } var isGoKeyword = map[string]bool{ "break": true, "case": true, "chan": true, "const": true, "continue": true, "default": true, "else": true, "defer": true, "fallthrough": true, "for": true, "func": true, "go": true, "goto": true, "if": true, "import": true, "interface": true, "map": true, "package": true, "range": true, "return": true, "select": true, "struct": true, "switch": true, "type": true, "var": true, } // defaultGoPackage returns the package name to use, // derived from the import path of the package we're building code for. func (g *Generator) defaultGoPackage() string { p := g.PackageImportPath if i := strings.LastIndex(p, "/"); i >= 0 { p = p[i+1:] } if p == "" { return "" } p = strings.Map(badToUnderscore, p) // Identifier must not be keyword: insert _. if isGoKeyword[p] { p = "_" + p } // Identifier must not begin with digit: insert _. if r, _ := utf8.DecodeRuneInString(p); unicode.IsDigit(r) { p = "_" + p } return p } // SetPackageNames sets the package name for this run. // The package name must agree across all files being generated. // It also defines unique package names for all imported files. func (g *Generator) SetPackageNames() { // Register the name for this package. It will be the first name // registered so is guaranteed to be unmodified. pkg, explicit := g.genFiles[0].goPackageName() // Check all files for an explicit go_package option. for _, f := range g.genFiles { thisPkg, thisExplicit := f.goPackageName() if thisExplicit { if !explicit { // Let this file's go_package option serve for all input files. pkg, explicit = thisPkg, true } else if thisPkg != pkg { g.Fail("inconsistent package names:", thisPkg, pkg) } } } // If we don't have an explicit go_package option but we have an // import path, use that. if !explicit { p := g.defaultGoPackage() if p != "" { pkg, explicit = p, true } } // If there was no go_package and no import path to use, // double-check that all the inputs have the same implicit // Go package name. if !explicit { for _, f := range g.genFiles { thisPkg, _ := f.goPackageName() if thisPkg != pkg { g.Fail("inconsistent package names:", thisPkg, pkg) } } } g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0]) // Register the support package names. They might collide with the // name of a package we import. g.Pkg = map[string]string{ "fmt": RegisterUniquePackageName("fmt", nil), "math": RegisterUniquePackageName("math", nil), "proto": RegisterUniquePackageName("proto", nil), "golang_proto": RegisterUniquePackageName("golang_proto", nil), } AllFiles: for _, f := range g.allFiles { for _, genf := range g.genFiles { if f == genf { // In this package already. uniquePackageName[f.FileDescriptorProto] = g.packageName continue AllFiles } } // The file is a dependency, so we want to ignore its go_package option // because that is only relevant for its specific generated output. pkg := f.GetPackage() if pkg == "" { pkg = baseName(*f.Name) } RegisterUniquePackageName(pkg, f) } } // WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos // and FileDescriptorProtos into file-referenced objects within the Generator. // It also creates the list of files to generate and so should be called before GenerateAllFiles. func (g *Generator) WrapTypes() { g.allFiles = make([]*FileDescriptor, 0, len(g.Request.ProtoFile)) g.allFilesByName = make(map[string]*FileDescriptor, len(g.allFiles)) for _, f := range g.Request.ProtoFile { // We must wrap the descriptors before we wrap the enums descs := wrapDescriptors(f) g.buildNestedDescriptors(descs) enums := wrapEnumDescriptors(f, descs) g.buildNestedEnums(descs, enums) exts := wrapExtensions(f) fd := &FileDescriptor{ FileDescriptorProto: f, desc: descs, enum: enums, ext: exts, exported: make(map[Object][]symbol), proto3: fileIsProto3(f), suffix: g.Suffix, } extractComments(fd) g.allFiles = append(g.allFiles, fd) g.allFilesByName[f.GetName()] = fd } for _, fd := range g.allFiles { fd.imp = wrapImported(fd.FileDescriptorProto, g) } g.genFiles = make([]*FileDescriptor, 0, len(g.Request.FileToGenerate)) for _, fileName := range g.Request.FileToGenerate { fd := g.allFilesByName[fileName] if fd == nil { g.Fail("could not find file named", fileName) } fd.index = len(g.genFiles) g.genFiles = append(g.genFiles, fd) } } // Scan the descriptors in this file. For each one, build the slice of nested descriptors func (g *Generator) buildNestedDescriptors(descs []*Descriptor) { for _, desc := range descs { if len(desc.NestedType) != 0 { for _, nest := range descs { if nest.parent == desc { desc.nested = append(desc.nested, nest) } } if len(desc.nested) != len(desc.NestedType) { g.Fail("internal error: nesting failure for", desc.GetName()) } } } } func (g *Generator) buildNestedEnums(descs []*Descriptor, enums []*EnumDescriptor) { for _, desc := range descs { if len(desc.EnumType) != 0 { for _, enum := range enums { if enum.parent == desc { desc.enums = append(desc.enums, enum) } } if len(desc.enums) != len(desc.EnumType) { g.Fail("internal error: enum nesting failure for", desc.GetName()) } } } } // Construct the Descriptor func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *Descriptor { d := &Descriptor{ common: common{file}, DescriptorProto: desc, parent: parent, index: index, } if parent == nil { d.path = fmt.Sprintf("%d,%d", messagePath, index) } else { d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index) } // The only way to distinguish a group from a message is whether // the containing message has a TYPE_GROUP field that matches. if parent != nil { parts := d.TypeName() if file.Package != nil { parts = append([]string{*file.Package}, parts...) } exp := "." + strings.Join(parts, ".") for _, field := range parent.Field { if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp { d.group = true break } } } for _, field := range desc.Extension { d.ext = append(d.ext, &ExtensionDescriptor{common{file}, field, d}) } return d } // Return a slice of all the Descriptors defined within this file func wrapDescriptors(file *descriptor.FileDescriptorProto) []*Descriptor { sl := make([]*Descriptor, 0, len(file.MessageType)+10) for i, desc := range file.MessageType { sl = wrapThisDescriptor(sl, desc, nil, file, i) } return sl } // Wrap this Descriptor, recursively func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) []*Descriptor { sl = append(sl, newDescriptor(desc, parent, file, index)) me := sl[len(sl)-1] for i, nested := range desc.NestedType { sl = wrapThisDescriptor(sl, nested, me, file, i) } return sl } // Construct the EnumDescriptor func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *EnumDescriptor { ed := &EnumDescriptor{ common: common{file}, EnumDescriptorProto: desc, parent: parent, index: index, } if parent == nil { ed.path = fmt.Sprintf("%d,%d", enumPath, index) } else { ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index) } return ed } // Return a slice of all the EnumDescriptors defined within this file func wrapEnumDescriptors(file *descriptor.FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor { sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10) // Top-level enums. for i, enum := range file.EnumType { sl = append(sl, newEnumDescriptor(enum, nil, file, i)) } // Enums within messages. Enums within embedded messages appear in the outer-most message. for _, nested := range descs { for i, enum := range nested.EnumType { sl = append(sl, newEnumDescriptor(enum, nested, file, i)) } } return sl } // Return a slice of all the top-level ExtensionDescriptors defined within this file. func wrapExtensions(file *descriptor.FileDescriptorProto) []*ExtensionDescriptor { var sl []*ExtensionDescriptor for _, field := range file.Extension { sl = append(sl, &ExtensionDescriptor{common{file}, field, nil}) } return sl } // Return a slice of all the types that are publicly imported into this file. func wrapImported(file *descriptor.FileDescriptorProto, g *Generator) (sl []*ImportedDescriptor) { for _, index := range file.PublicDependency { df := g.fileByName(file.Dependency[index]) for _, d := range df.desc { if d.GetOptions().GetMapEntry() { continue } sl = append(sl, &ImportedDescriptor{common{file}, d}) } for _, e := range df.enum { sl = append(sl, &ImportedDescriptor{common{file}, e}) } for _, ext := range df.ext { sl = append(sl, &ImportedDescriptor{common{file}, ext}) } } return } func extractComments(file *FileDescriptor) { file.comments = make(map[string]*descriptor.SourceCodeInfo_Location) for _, loc := range file.GetSourceCodeInfo().GetLocation() { if loc.LeadingComments == nil { continue } var p []string for _, n := range loc.Path { p = append(p, strconv.Itoa(int(n))) } file.comments[strings.Join(p, ",")] = loc } } // BuildTypeNameMap builds the map from fully qualified type names to objects. // The key names for the map come from the input data, which puts a period at the beginning. // It should be called after SetPackageNames and before GenerateAllFiles. func (g *Generator) BuildTypeNameMap() { g.typeNameToObject = make(map[string]Object) for _, f := range g.allFiles { // The names in this loop are defined by the proto world, not us, so the // package name may be empty. If so, the dotted package name of X will // be ".X"; otherwise it will be ".pkg.X". dottedPkg := "." + f.GetPackage() if dottedPkg != "." { dottedPkg += "." } for _, enum := range f.enum { name := dottedPkg + dottedSlice(enum.TypeName()) g.typeNameToObject[name] = enum } for _, desc := range f.desc { name := dottedPkg + dottedSlice(desc.TypeName()) g.typeNameToObject[name] = desc } } } // ObjectNamed, given a fully-qualified input type name as it appears in the input data, // returns the descriptor for the message or enum with that name. func (g *Generator) ObjectNamed(typeName string) Object { o, ok := g.typeNameToObject[typeName] if !ok { g.Fail("can't find object with type", typeName) } // If the file of this object isn't a direct dependency of the current file, // or in the current file, then this object has been publicly imported into // a dependency of the current file. // We should return the ImportedDescriptor object for it instead. direct := *o.File().Name == *g.file.Name if !direct { for _, dep := range g.file.Dependency { if *g.fileByName(dep).Name == *o.File().Name { direct = true break } } } if !direct { found := false Loop: for _, dep := range g.file.Dependency { df := g.fileByName(*g.fileByName(dep).Name) for _, td := range df.imp { if td.o == o { // Found it! o = td found = true break Loop } } } if !found { log.Printf("protoc-gen-yarpc: WARNING: failed finding publicly imported dependency for %v, used in %v", typeName, *g.file.Name) } } return o } // P prints the arguments to the generated output. It handles strings and int32s, plus // handling indirections because they may be *string, etc. func (g *Generator) P(str ...interface{}) { if !g.writeOutput { return } g.WriteString(g.indent) for _, v := range str { switch s := v.(type) { case string: g.WriteString(s) case *string: g.WriteString(*s) case bool: fmt.Fprintf(g, "%t", s) case *bool: fmt.Fprintf(g, "%t", *s) case int: fmt.Fprintf(g, "%d", s) case *int32: fmt.Fprintf(g, "%d", *s) case *int64: fmt.Fprintf(g, "%d", *s) case float64: fmt.Fprintf(g, "%g", s) case *float64: fmt.Fprintf(g, "%g", *s) default: g.Fail(fmt.Sprintf("unknown type in printer: %T", v)) } } g.WriteByte('\n') } // addInitf stores the given statement to be printed inside the file's init function. // The statement is given as a format specifier and arguments. func (g *Generator) addInitf(stmt string, a ...interface{}) { g.init = append(g.init, fmt.Sprintf(stmt, a...)) } func (g *Generator) PrintImport(alias, pkg string) { statement := "import " + alias + " " + strconv.Quote(pkg) if g.writtenImports[statement] { return } g.P(statement) g.writtenImports[statement] = true } // In Indents the output one tab stop. func (g *Generator) In() { g.indent += "\t" } // Out unindents the output one tab stop. func (g *Generator) Out() { if len(g.indent) > 0 { g.indent = g.indent[1:] } } // FileOf return the FileDescriptor for this FileDescriptorProto. func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor { for _, file := range g.allFiles { if file.FileDescriptorProto == fd { return file } } g.Fail("could not find file in table:", fd.GetName()) return nil } // Generate the header, including package definition func (g *Generator) generateHeader() { g.P("// Code generated by protoc-gen-yarpc. DO NOT EDIT.") g.P("// source: ", *g.file.Name) g.P() name := g.file.PackageName() if g.file.index == 0 { // Generate package docs for the first file in the package. g.P("/*") g.P("Package ", name, " is a generated protocol buffer package.") g.P() if loc, ok := g.file.comments[strconv.Itoa(packagePath)]; ok { // not using g.PrintComments because this is a /* */ comment block. text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") for _, line := range strings.Split(text, "\n") { line = strings.TrimPrefix(line, " ") // ensure we don't escape from the block comment line = strings.Replace(line, "*/", "* /", -1) g.P(line) } g.P() } var topMsgs []string g.P("It is generated from these files:") for _, f := range g.genFiles { g.P("\t", f.Name) for _, msg := range f.desc { if msg.parent != nil { continue } topMsgs = append(topMsgs, CamelCaseSlice(msg.TypeName())) } } g.P() g.P("It has these top-level messages:") for _, msg := range topMsgs { g.P("\t", msg) } g.P("*/") } g.P("package ", name) g.P() } // PrintComments prints any comments from the source .proto file. // The path is a comma-separated list of integers. // It returns an indication of whether any comments were printed. // See descriptor.proto for its format. func (g *Generator) PrintComments(path string) bool { if !g.writeOutput { return false } if loc, ok := g.file.comments[path]; ok { text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") for _, line := range strings.Split(text, "\n") { g.P("// ", strings.TrimPrefix(line, " ")) } return true } return false } // Comments returns any comments from the source .proto file and empty string if comments not found. // The path is a comma-separated list of intergers. // See descriptor.proto for its format. func (g *Generator) Comments(path string) string { loc, ok := g.file.comments[path] if !ok { return "" } text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") return text } func (g *Generator) fileByName(filename string) *FileDescriptor { return g.allFilesByName[filename] } // weak returns whether the ith import of the current file is a weak import. func (g *Generator) weak(i int32) bool { for _, j := range g.file.WeakDependency { if j == i { return true } } return false } // Generate the imports func (g *Generator) generateImports() { // We almost always need a proto import. Rather than computing when we // do, which is tricky when there's a plugin, just import it and // reference it later. The same argument applies to the fmt and math packages. if gogoproto.ImportsGoGoProto(g.file.FileDescriptorProto) { g.PrintImport(g.Pkg["proto"], g.ImportPrefix+"github.com/gogo/protobuf/proto") if gogoproto.RegistersGolangProto(g.file.FileDescriptorProto) { g.PrintImport(g.Pkg["golang_proto"], g.ImportPrefix+"github.com/golang/protobuf/proto") } } else { g.PrintImport(g.Pkg["proto"], g.ImportPrefix+"github.com/golang/protobuf/proto") } g.PrintImport(g.Pkg["fmt"], "fmt") g.PrintImport(g.Pkg["math"], "math") for i, s := range g.file.Dependency { fd := g.fileByName(s) // Do not import our own package. if fd.PackageName() == g.packageName { continue } filename := fd.goFileName() // By default, import path is the dirname of the Go filename. importPath := path.Dir(filename) if substitution, ok := g.ImportMap[s]; ok { importPath = substitution } importPath = g.ImportPrefix + importPath // Skip weak imports. if g.weak(int32(i)) { g.P("// skipping weak import ", fd.PackageName(), " ", strconv.Quote(importPath)) continue } // We need to import all the dependencies, even if we don't reference them, // because other code and tools depend on having the full transitive closure // of protocol buffer types in the binary. if _, ok := g.usedPackages[fd.PackageName()]; ok { g.PrintImport(fd.PackageName(), importPath) } else { g.P("import _ ", strconv.Quote(importPath)) } } g.P() for _, s := range g.customImports { s1 := strings.Map(badToUnderscore, s) g.PrintImport(s1, s) } g.P() g.P("// Reference imports to suppress errors if they are not otherwise used.") g.P("var _ = ", g.Pkg["proto"], ".Marshal") if gogoproto.ImportsGoGoProto(g.file.FileDescriptorProto) && gogoproto.RegistersGolangProto(g.file.FileDescriptorProto) { g.P("var _ = ", g.Pkg["golang_proto"], ".Marshal") } g.P("var _ = ", g.Pkg["fmt"], ".Errorf") g.P("var _ = ", g.Pkg["math"], ".Inf") for _, cimport := range g.customImports { if cimport == "time" { g.P("var _ = time.Kitchen") break } } g.P() } func (g *Generator) generateImported(id *ImportedDescriptor) { // Don't generate public import symbols for files that we are generating // code for, since those symbols will already be in this package. // We can't simply avoid creating the ImportedDescriptor objects, // because g.genFiles isn't populated at that stage. tn := id.TypeName() sn := tn[len(tn)-1] df := g.FileOf(id.o.File()) filename := *df.Name for _, fd := range g.genFiles { if *fd.Name == filename { g.P("// Ignoring public import of ", sn, " from ", filename) g.P() return } } g.P("// ", sn, " from public import ", filename) g.usedPackages[df.PackageName()] = true for _, sym := range df.exported[id.o] { sym.GenerateAlias(g, df.PackageName()) } g.P() } // The tag is a string like "varint,2,opt,name=fieldname,def=7" that // identifies details of the field for the protocol buffer marshaling and unmarshaling // code. The fields are: // wire encoding // protocol tag number // opt,req,rep for optional, required, or repeated // packed whether the encoding is "packed" (optional; repeated primitives only) // name= the original declared name // enum= the name of the enum type if it is an enum-typed field. // proto3 if this field is in a proto3 message // def= string representation of the default value, if any. // The default value must be in a representation that can be used at run-time // to generate the default value. Thus bools become 0 and 1, for instance. func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptorProto, wiretype string) string { optrepreq := "" switch { case isOptional(field): optrepreq = "opt" case isRequired(field): optrepreq = "req" case isRepeated(field): optrepreq = "rep" } var defaultValue string if dv := field.DefaultValue; dv != nil { // set means an explicit default defaultValue = *dv // Some types need tweaking. switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BOOL: if defaultValue == "true" { defaultValue = "1" } else { defaultValue = "0" } case descriptor.FieldDescriptorProto_TYPE_STRING, descriptor.FieldDescriptorProto_TYPE_BYTES: // Nothing to do. Quoting is done for the whole tag. case descriptor.FieldDescriptorProto_TYPE_ENUM: // For enums we need to provide the integer constant. obj := g.ObjectNamed(field.GetTypeName()) if id, ok := obj.(*ImportedDescriptor); ok { // It is an enum that was publicly imported. // We need the underlying type. obj = id.o } enum, ok := obj.(*EnumDescriptor) if !ok { log.Printf("obj is a %T", obj) if id, ok := obj.(*ImportedDescriptor); ok { log.Printf("id.o is a %T", id.o) } g.Fail("unknown enum type", CamelCaseSlice(obj.TypeName())) } defaultValue = enum.integerValueAsString(defaultValue) } defaultValue = ",def=" + defaultValue } enum := "" if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM { // We avoid using obj.PackageName(), because we want to use the // original (proto-world) package name. obj := g.ObjectNamed(field.GetTypeName()) if id, ok := obj.(*ImportedDescriptor); ok { obj = id.o } enum = ",enum=" if pkg := obj.File().GetPackage(); pkg != "" { enum += pkg + "." } enum += CamelCaseSlice(obj.TypeName()) } packed := "" if (field.Options != nil && field.Options.GetPacked()) || // Per https://developers.google.com/protocol-buffers/docs/proto3#simple: // "In proto3, repeated fields of scalar numeric types use packed encoding by default." (message.proto3() && (field.Options == nil || field.Options.Packed == nil) && isRepeated(field) && IsScalar(field)) { packed = ",packed" } fieldName := field.GetName() name := fieldName if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { // We must use the type name for groups instead of // the field name to preserve capitalization. // type_name in FieldDescriptorProto is fully-qualified, // but we only want the local part. name = *field.TypeName if i := strings.LastIndex(name, "."); i >= 0 { name = name[i+1:] } } if json := field.GetJsonName(); json != "" && json != name { // TODO: escaping might be needed, in which case // perhaps this should be in its own "json" tag. name += ",json=" + json } name = ",name=" + name embed := "" if gogoproto.IsEmbed(field) { embed = ",embedded=" + fieldName } ctype := "" if gogoproto.IsCustomType(field) { ctype = ",customtype=" + gogoproto.GetCustomType(field) } casttype := "" if gogoproto.IsCastType(field) { casttype = ",casttype=" + gogoproto.GetCastType(field) } castkey := "" if gogoproto.IsCastKey(field) { castkey = ",castkey=" + gogoproto.GetCastKey(field) } castvalue := "" if gogoproto.IsCastValue(field) { castvalue = ",castvalue=" + gogoproto.GetCastValue(field) // record the original message type for jsonpb reconstruction desc := g.ObjectNamed(field.GetTypeName()) if d, ok := desc.(*Descriptor); ok && d.GetOptions().GetMapEntry() { valueField := d.Field[1] if valueField.IsMessage() { castvalue += ",castvaluetype=" + strings.TrimPrefix(valueField.GetTypeName(), ".") } } } if message.proto3() { // We only need the extra tag for []byte fields; // no need to add noise for the others. if *field.Type != descriptor.FieldDescriptorProto_TYPE_MESSAGE && *field.Type != descriptor.FieldDescriptorProto_TYPE_GROUP && !field.IsRepeated() { name += ",proto3" } } oneof := "" if field.OneofIndex != nil { oneof = ",oneof" } stdtime := "" if gogoproto.IsStdTime(field) { stdtime = ",stdtime" } stdduration := "" if gogoproto.IsStdDuration(field) { stdduration = ",stdduration" } return strconv.Quote(fmt.Sprintf("%s,%d,%s%s%s%s%s%s%s%s%s%s%s%s%s", wiretype, field.GetNumber(), optrepreq, packed, name, enum, oneof, defaultValue, embed, ctype, casttype, castkey, castvalue, stdtime, stdduration)) } func needsStar(field *descriptor.FieldDescriptorProto, proto3 bool, allowOneOf bool) bool { if isRepeated(field) && (*field.Type != descriptor.FieldDescriptorProto_TYPE_MESSAGE || gogoproto.IsCustomType(field)) && (*field.Type != descriptor.FieldDescriptorProto_TYPE_GROUP) { return false } if *field.Type == descriptor.FieldDescriptorProto_TYPE_BYTES && !gogoproto.IsCustomType(field) { return false } if !gogoproto.IsNullable(field) { return false } if field.OneofIndex != nil && allowOneOf && (*field.Type != descriptor.FieldDescriptorProto_TYPE_MESSAGE) && (*field.Type != descriptor.FieldDescriptorProto_TYPE_GROUP) { return false } if proto3 && (*field.Type != descriptor.FieldDescriptorProto_TYPE_MESSAGE) && (*field.Type != descriptor.FieldDescriptorProto_TYPE_GROUP) && !gogoproto.IsCustomType(field) { return false } return true } // TypeName is the printed name appropriate for an item. If the object is in the current file, // TypeName drops the package name and underscores the rest. // Otherwise the object is from another package; and the result is the underscored // package name followed by the item name. // The result always has an initial capital. func (g *Generator) TypeName(obj Object) string { return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName()) } // TypeNameWithPackage is like TypeName, but always includes the package // name even if the object is in our own package. func (g *Generator) TypeNameWithPackage(obj Object) string { return obj.PackageName() + CamelCaseSlice(obj.TypeName()) } // GoType returns a string representing the type name, and the wire type func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) { // TODO: Options. switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: typ, wire = "float64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_FLOAT: typ, wire = "float32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_INT64: typ, wire = "int64", "varint" case descriptor.FieldDescriptorProto_TYPE_UINT64: typ, wire = "uint64", "varint" case descriptor.FieldDescriptorProto_TYPE_INT32: typ, wire = "int32", "varint" case descriptor.FieldDescriptorProto_TYPE_UINT32: typ, wire = "uint32", "varint" case descriptor.FieldDescriptorProto_TYPE_FIXED64: typ, wire = "uint64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_FIXED32: typ, wire = "uint32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_BOOL: typ, wire = "bool", "varint" case descriptor.FieldDescriptorProto_TYPE_STRING: typ, wire = "string", "bytes" case descriptor.FieldDescriptorProto_TYPE_GROUP: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = g.TypeName(desc), "group" case descriptor.FieldDescriptorProto_TYPE_MESSAGE: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = g.TypeName(desc), "bytes" case descriptor.FieldDescriptorProto_TYPE_BYTES: typ, wire = "[]byte", "bytes" case descriptor.FieldDescriptorProto_TYPE_ENUM: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = g.TypeName(desc), "varint" case descriptor.FieldDescriptorProto_TYPE_SFIXED32: typ, wire = "int32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_SFIXED64: typ, wire = "int64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_SINT32: typ, wire = "int32", "zigzag32" case descriptor.FieldDescriptorProto_TYPE_SINT64: typ, wire = "int64", "zigzag64" default: g.Fail("unknown type for", field.GetName()) } switch { case gogoproto.IsCustomType(field) && gogoproto.IsCastType(field): g.Fail(field.GetName() + " cannot be custom type and cast type") case gogoproto.IsCustomType(field): var packageName string var err error packageName, typ, err = getCustomType(field) if err != nil { g.Fail(err.Error()) } if len(packageName) > 0 { g.customImports = append(g.customImports, packageName) } case gogoproto.IsCastType(field): var packageName string var err error packageName, typ, err = getCastType(field) if err != nil { g.Fail(err.Error()) } if len(packageName) > 0 { g.customImports = append(g.customImports, packageName) } case gogoproto.IsStdTime(field): g.customImports = append(g.customImports, "time") typ = "time.Time" case gogoproto.IsStdDuration(field): g.customImports = append(g.customImports, "time") typ = "time.Duration" } if needsStar(field, g.file.proto3 && field.Extendee == nil, message != nil && message.allowOneof()) { typ = "*" + typ } if isRepeated(field) { typ = "[]" + typ } return } // GoMapDescriptor is a full description of the map output struct. type GoMapDescriptor struct { GoType string KeyField *descriptor.FieldDescriptorProto KeyAliasField *descriptor.FieldDescriptorProto KeyTag string ValueField *descriptor.FieldDescriptorProto ValueAliasField *descriptor.FieldDescriptorProto ValueTag string } func (g *Generator) GoMapType(d *Descriptor, field *descriptor.FieldDescriptorProto) *GoMapDescriptor { if d == nil { byName := g.ObjectNamed(field.GetTypeName()) desc, ok := byName.(*Descriptor) if byName == nil || !ok || !desc.GetOptions().GetMapEntry() { g.Fail(fmt.Sprintf("field %s is not a map", field.GetTypeName())) return nil } d = desc } m := &GoMapDescriptor{ KeyField: d.Field[0], ValueField: d.Field[1], } // Figure out the Go types and tags for the key and value types. m.KeyAliasField, m.ValueAliasField = g.GetMapKeyField(field, m.KeyField), g.GetMapValueField(field, m.ValueField) keyType, keyWire := g.GoType(d, m.KeyAliasField) valType, valWire := g.GoType(d, m.ValueAliasField) m.KeyTag, m.ValueTag = g.goTag(d, m.KeyField, keyWire), g.goTag(d, m.ValueField, valWire) if gogoproto.IsCastType(field) { var packageName string var err error packageName, typ, err := getCastType(field) if err != nil { g.Fail(err.Error()) } if len(packageName) > 0 { g.customImports = append(g.customImports, packageName) } m.GoType = typ return m } // We don't use stars, except for message-typed values. // Message and enum types are the only two possibly foreign types used in maps, // so record their use. They are not permitted as map keys. keyType = strings.TrimPrefix(keyType, "*") switch *m.ValueAliasField.Type { case descriptor.FieldDescriptorProto_TYPE_ENUM: valType = strings.TrimPrefix(valType, "*") g.RecordTypeUse(m.ValueAliasField.GetTypeName()) case descriptor.FieldDescriptorProto_TYPE_MESSAGE: if !gogoproto.IsNullable(m.ValueAliasField) { valType = strings.TrimPrefix(valType, "*") } if !gogoproto.IsStdTime(field) && !gogoproto.IsStdDuration(field) { g.RecordTypeUse(m.ValueAliasField.GetTypeName()) } default: if gogoproto.IsCustomType(m.ValueAliasField) { if !gogoproto.IsNullable(m.ValueAliasField) { valType = strings.TrimPrefix(valType, "*") } g.RecordTypeUse(m.ValueAliasField.GetTypeName()) } else { valType = strings.TrimPrefix(valType, "*") } } m.GoType = fmt.Sprintf("map[%s]%s", keyType, valType) return m } func (g *Generator) RecordTypeUse(t string) { if obj, ok := g.typeNameToObject[t]; ok { // Call ObjectNamed to get the true object to record the use. obj = g.ObjectNamed(t) g.usedPackages[obj.PackageName()] = true } } // Method names that may be generated. Fields with these names get an // underscore appended. Any change to this set is a potential incompatible // API change because it changes generated field names. var methodNames = [...]string{ "Reset", "String", "ProtoMessage", "Marshal", "Unmarshal", "ExtensionRangeArray", "ExtensionMap", "Descriptor", "MarshalTo", "Equal", "VerboseEqual", "GoString", "ProtoSize", } func (g *Generator) generateInitFunction() { if len(g.init) == 0 { return } g.P("func init() {") g.In() for _, l := range g.init { g.P(l) } g.Out() g.P("}") g.init = nil } // And now lots of helper functions. // Is c an ASCII lower-case letter? func isASCIILower(c byte) bool { return 'a' <= c && c <= 'z' } // Is c an ASCII digit? func isASCIIDigit(c byte) bool { return '0' <= c && c <= '9' } // CamelCase returns the CamelCased name. // If there is an interior underscore followed by a lower case letter, // drop the underscore and convert the letter to upper case. // There is a remote possibility of this rewrite causing a name collision, // but it's so remote we're prepared to pretend it's nonexistent - since the // C++ generator lowercases names, it's extremely unlikely to have two fields // with different capitalizations. // In short, _my_field_name_2 becomes XMyFieldName_2. func CamelCase(s string) string { if s == "" { return "" } t := make([]byte, 0, 32) i := 0 if s[0] == '_' { // Need a capital letter; drop the '_'. t = append(t, 'X') i++ } // Invariant: if the next letter is lower case, it must be converted // to upper case. // That is, we process a word at a time, where words are marked by _ or // upper case letter. Digits are treated as words. for ; i < len(s); i++ { c := s[i] if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) { continue // Skip the underscore in s. } if isASCIIDigit(c) { t = append(t, c) continue } // Assume we have a letter now - if not, it's a bogus identifier. // The next word is a sequence of characters that must start upper case. if isASCIILower(c) { c ^= ' ' // Make it a capital letter. } t = append(t, c) // Guaranteed not lower case. // Accept lower case sequence that follows. for i+1 < len(s) && isASCIILower(s[i+1]) { i++ t = append(t, s[i]) } } return string(t) } // CamelCaseSlice is like CamelCase, but the argument is a slice of strings to // be joined with "_". func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) } // dottedSlice turns a sliced name into a dotted name. func dottedSlice(elem []string) string { return strings.Join(elem, ".") } // Is this field optional? func isOptional(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL } // Is this field required? func isRequired(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED } // Is this field repeated? func isRepeated(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED } // Is this field a scalar numeric type? func IsScalar(field *descriptor.FieldDescriptorProto) bool { if field.Type == nil { return false } switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE, descriptor.FieldDescriptorProto_TYPE_FLOAT, descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64, descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_BOOL, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM, descriptor.FieldDescriptorProto_TYPE_SFIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED64, descriptor.FieldDescriptorProto_TYPE_SINT32, descriptor.FieldDescriptorProto_TYPE_SINT64: return true default: return false } } // badToUnderscore is the mapping function used to generate Go names from package names, // which can be dotted in the input .proto file. It replaces non-identifier characters such as // dot or dash with underscore. func badToUnderscore(r rune) rune { if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' { return r } return '_' } // baseName returns the last path element of the name, with the last dotted suffix removed. func baseName(name string) string { // First, find the last element if i := strings.LastIndex(name, "/"); i >= 0 { name = name[i+1:] } // Now drop the suffix if i := strings.LastIndex(name, "."); i >= 0 { name = name[0:i] } return name } // The SourceCodeInfo message describes the location of elements of a parsed // .proto file by way of a "path", which is a sequence of integers that // describe the route from a FileDescriptorProto to the relevant submessage. // The path alternates between a field number of a repeated field, and an index // into that repeated field. The constants below define the field numbers that // are used. // // See descriptor.proto for more information about this. const ( // tag numbers in FileDescriptorProto packagePath = 2 // package messagePath = 4 // message_type enumPath = 5 // enum_type // tag numbers in DescriptorProto messageFieldPath = 2 // field messageMessagePath = 3 // nested_type messageEnumPath = 4 // enum_type messageOneofPath = 8 // oneof_decl // tag numbers in EnumDescriptorProto enumValuePath = 2 // value ) yarpc-0.0.1/cmd/protoc-gen-yarpc/generator/helper.go000066400000000000000000000310451331225777200223720ustar00rootroot00000000000000// Protocol Buffers for Go with Gadgets // // Copyright (c) 2013, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package generator import ( "path" "strings" "bytes" "go/parser" "go/printer" "go/token" "github.com/gogo/protobuf/gogoproto" "github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" plugin "github.com/gogo/protobuf/protoc-gen-gogo/plugin" ) func (d *FileDescriptor) Messages() []*Descriptor { return d.desc } func (d *FileDescriptor) Enums() []*EnumDescriptor { return d.enum } func (d *Descriptor) IsGroup() bool { return d.group } func (g *Generator) IsGroup(field *descriptor.FieldDescriptorProto) bool { if d, ok := g.typeNameToObject[field.GetTypeName()].(*Descriptor); ok { return d.IsGroup() } return false } func (g *Generator) TypeNameByObject(typeName string) Object { o, ok := g.typeNameToObject[typeName] if !ok { g.Fail("can't find object with type", typeName) } return o } func (g *Generator) OneOfTypeName(message *Descriptor, field *descriptor.FieldDescriptorProto) string { typeName := message.TypeName() ccTypeName := CamelCaseSlice(typeName) fieldName := g.GetOneOfFieldName(message, field) tname := ccTypeName + "_" + fieldName // It is possible for this to collide with a message or enum // nested in this message. Check for collisions. ok := true for _, desc := range message.nested { if strings.Join(desc.TypeName(), "_") == tname { ok = false break } } for _, enum := range message.enums { if strings.Join(enum.TypeName(), "_") == tname { ok = false break } } if !ok { tname += "_" } return tname } type PluginImports interface { NewImport(pkg string) Single GenerateImports(file *FileDescriptor) } type pluginImports struct { generator *Generator singles []Single } func NewPluginImports(generator *Generator) *pluginImports { return &pluginImports{generator, make([]Single, 0)} } func (this *pluginImports) NewImport(pkg string) Single { imp := newImportedPackage(this.generator.ImportPrefix, pkg) this.singles = append(this.singles, imp) return imp } func (this *pluginImports) GenerateImports(file *FileDescriptor) { for _, s := range this.singles { if s.IsUsed() { this.generator.PrintImport(s.Name(), s.Location()) } } } type Single interface { Use() string IsUsed() bool Name() string Location() string } type importedPackage struct { used bool pkg string name string importPrefix string } func newImportedPackage(importPrefix, pkg string) *importedPackage { return &importedPackage{ pkg: pkg, importPrefix: importPrefix, } } func (this *importedPackage) Use() string { if !this.used { this.name = RegisterUniquePackageName(this.pkg, nil) this.used = true } return this.name } func (this *importedPackage) IsUsed() bool { return this.used } func (this *importedPackage) Name() string { return this.name } func (this *importedPackage) Location() string { return this.importPrefix + this.pkg } func (g *Generator) GetFieldName(message *Descriptor, field *descriptor.FieldDescriptorProto) string { goTyp, _ := g.GoType(message, field) fieldname := CamelCase(*field.Name) if gogoproto.IsCustomName(field) { fieldname = gogoproto.GetCustomName(field) } if gogoproto.IsEmbed(field) { fieldname = EmbedFieldName(goTyp) } if field.OneofIndex != nil { fieldname = message.OneofDecl[int(*field.OneofIndex)].GetName() fieldname = CamelCase(fieldname) } for _, f := range methodNames { if f == fieldname { return fieldname + "_" } } if !gogoproto.IsProtoSizer(message.file, message.DescriptorProto) { if fieldname == "Size" { return fieldname + "_" } } return fieldname } func (g *Generator) GetOneOfFieldName(message *Descriptor, field *descriptor.FieldDescriptorProto) string { goTyp, _ := g.GoType(message, field) fieldname := CamelCase(*field.Name) if gogoproto.IsCustomName(field) { fieldname = gogoproto.GetCustomName(field) } if gogoproto.IsEmbed(field) { fieldname = EmbedFieldName(goTyp) } for _, f := range methodNames { if f == fieldname { return fieldname + "_" } } if !gogoproto.IsProtoSizer(message.file, message.DescriptorProto) { if fieldname == "Size" { return fieldname + "_" } } return fieldname } func (g *Generator) IsMap(field *descriptor.FieldDescriptorProto) bool { if !field.IsMessage() { return false } byName := g.ObjectNamed(field.GetTypeName()) desc, ok := byName.(*Descriptor) if byName == nil || !ok || !desc.GetOptions().GetMapEntry() { return false } return true } func (g *Generator) GetMapKeyField(field, keyField *descriptor.FieldDescriptorProto) *descriptor.FieldDescriptorProto { if !gogoproto.IsCastKey(field) { return keyField } keyField = proto.Clone(keyField).(*descriptor.FieldDescriptorProto) if keyField.Options == nil { keyField.Options = &descriptor.FieldOptions{} } keyType := gogoproto.GetCastKey(field) if err := proto.SetExtension(keyField.Options, gogoproto.E_Casttype, &keyType); err != nil { g.Fail(err.Error()) } return keyField } func (g *Generator) GetMapValueField(field, valField *descriptor.FieldDescriptorProto) *descriptor.FieldDescriptorProto { if gogoproto.IsCustomType(field) && gogoproto.IsCastValue(field) { g.Fail("cannot have a customtype and casttype: ", field.String()) } valField = proto.Clone(valField).(*descriptor.FieldDescriptorProto) if valField.Options == nil { valField.Options = &descriptor.FieldOptions{} } stdtime := gogoproto.IsStdTime(field) if stdtime { if err := proto.SetExtension(valField.Options, gogoproto.E_Stdtime, &stdtime); err != nil { g.Fail(err.Error()) } } stddur := gogoproto.IsStdDuration(field) if stddur { if err := proto.SetExtension(valField.Options, gogoproto.E_Stdduration, &stddur); err != nil { g.Fail(err.Error()) } } if valType := gogoproto.GetCastValue(field); len(valType) > 0 { if err := proto.SetExtension(valField.Options, gogoproto.E_Casttype, &valType); err != nil { g.Fail(err.Error()) } } if valType := gogoproto.GetCustomType(field); len(valType) > 0 { if err := proto.SetExtension(valField.Options, gogoproto.E_Customtype, &valType); err != nil { g.Fail(err.Error()) } } nullable := gogoproto.IsNullable(field) if err := proto.SetExtension(valField.Options, gogoproto.E_Nullable, &nullable); err != nil { g.Fail(err.Error()) } return valField } // GoMapValueTypes returns the map value Go type and the alias map value Go type (for casting), taking into // account whether the map is nullable or the value is a message. func GoMapValueTypes(mapField, valueField *descriptor.FieldDescriptorProto, goValueType, goValueAliasType string) (nullable bool, outGoType string, outGoAliasType string) { nullable = gogoproto.IsNullable(mapField) && (valueField.IsMessage() || gogoproto.IsCustomType(mapField)) if nullable { // ensure the non-aliased Go value type is a pointer for consistency if strings.HasPrefix(goValueType, "*") { outGoType = goValueType } else { outGoType = "*" + goValueType } outGoAliasType = goValueAliasType } else { outGoType = strings.Replace(goValueType, "*", "", 1) outGoAliasType = strings.Replace(goValueAliasType, "*", "", 1) } return } func GoTypeToName(goTyp string) string { return strings.Replace(strings.Replace(goTyp, "*", "", -1), "[]", "", -1) } func EmbedFieldName(goTyp string) string { goTyp = GoTypeToName(goTyp) goTyps := strings.Split(goTyp, ".") if len(goTyps) == 1 { return goTyp } if len(goTyps) == 2 { return goTyps[1] } panic("unreachable") } func (g *Generator) GeneratePlugin(p Plugin) { p.Init(g) // Generate the output. The generator runs for every file, even the files // that we don't generate output for, so that we can collate the full list // of exported symbols to support public imports. genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles)) for _, file := range g.genFiles { genFileMap[file] = true } for _, file := range g.allFiles { g.Reset() g.writeOutput = genFileMap[file] g.generatePlugin(file, p) if !g.writeOutput { continue } g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{ Name: proto.String(file.goFileName()), Content: proto.String(g.String()), }) } } func (g *Generator) SetFile(file *descriptor.FileDescriptorProto) { g.file = g.FileOf(file) } func (g *Generator) generatePlugin(file *FileDescriptor, p Plugin) { g.writtenImports = make(map[string]bool) g.file = g.FileOf(file.FileDescriptorProto) g.usedPackages = make(map[string]bool) // Run the plugins before the imports so we know which imports are necessary. p.Generate(file) // Generate header and imports last, though they appear first in the output. rem := g.Buffer g.Buffer = new(bytes.Buffer) g.generateHeader() p.GenerateImports(g.file) g.generateImports() if !g.writeOutput { return } g.Write(rem.Bytes()) // Reformat generated code. contents := string(g.Buffer.Bytes()) fset := token.NewFileSet() ast, err := parser.ParseFile(fset, "", g, parser.ParseComments) if err != nil { g.Fail("bad Go source code was generated:", contents, err.Error()) return } g.Reset() err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast) if err != nil { g.Fail("generated Go source code could not be reformatted:", err.Error()) } } func GetCustomType(field *descriptor.FieldDescriptorProto) (packageName string, typ string, err error) { return getCustomType(field) } func getCustomType(field *descriptor.FieldDescriptorProto) (packageName string, typ string, err error) { if field.Options != nil { var v interface{} v, err = proto.GetExtension(field.Options, gogoproto.E_Customtype) if err == nil && v.(*string) != nil { ctype := *(v.(*string)) packageName, typ = splitCPackageType(ctype) return packageName, typ, nil } } return "", "", err } func splitCPackageType(ctype string) (packageName string, typ string) { ss := strings.Split(ctype, ".") if len(ss) == 1 { return "", ctype } packageName = strings.Join(ss[0:len(ss)-1], ".") typeName := ss[len(ss)-1] importStr := strings.Map(badToUnderscore, packageName) typ = importStr + "." + typeName return packageName, typ } func getCastType(field *descriptor.FieldDescriptorProto) (packageName string, typ string, err error) { if field.Options != nil { var v interface{} v, err = proto.GetExtension(field.Options, gogoproto.E_Casttype) if err == nil && v.(*string) != nil { ctype := *(v.(*string)) packageName, typ = splitCPackageType(ctype) return packageName, typ, nil } } return "", "", err } func FileName(file *FileDescriptor) string { fname := path.Base(file.FileDescriptorProto.GetName()) fname = strings.Replace(fname, ".proto", "", -1) fname = strings.Replace(fname, "-", "_", -1) fname = strings.Replace(fname, ".", "_", -1) return CamelCase(fname) } func (g *Generator) AllFiles() *descriptor.FileDescriptorSet { set := &descriptor.FileDescriptorSet{} set.File = make([]*descriptor.FileDescriptorProto, len(g.allFiles)) for i := range g.allFiles { set.File[i] = g.allFiles[i].FileDescriptorProto } return set } func (d *Descriptor) Path() string { return d.path } func (g *Generator) useTypes() string { pkg := strings.Map(badToUnderscore, "github.com/gogo/protobuf/types") g.customImports = append(g.customImports, "github.com/gogo/protobuf/types") return pkg } yarpc-0.0.1/cmd/protoc-gen-yarpc/generator/name_test.go000066400000000000000000000056101331225777200230710ustar00rootroot00000000000000// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2013 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package generator import ( "testing" "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" ) func TestCamelCase(t *testing.T) { tests := []struct { in, want string }{ {"one", "One"}, {"one_two", "OneTwo"}, {"_my_field_name_2", "XMyFieldName_2"}, {"Something_Capped", "Something_Capped"}, {"my_Name", "My_Name"}, {"OneTwo", "OneTwo"}, {"_", "X"}, {"_a_", "XA_"}, } for _, tc := range tests { if got := CamelCase(tc.in); got != tc.want { t.Errorf("CamelCase(%q) = %q, want %q", tc.in, got, tc.want) } } } func TestGoPackageOption(t *testing.T) { tests := []struct { in string impPath, pkg string ok bool }{ {"", "", "", false}, {"foo", "", "foo", true}, {"github.com/golang/bar", "github.com/golang/bar", "bar", true}, {"github.com/golang/bar;baz", "github.com/golang/bar", "baz", true}, } for _, tc := range tests { d := &FileDescriptor{ FileDescriptorProto: &descriptor.FileDescriptorProto{ Options: &descriptor.FileOptions{ GoPackage: &tc.in, }, }, } impPath, pkg, ok := d.goPackageOption() if impPath != tc.impPath || pkg != tc.pkg || ok != tc.ok { t.Errorf("go_package = %q => (%q, %q, %t), want (%q, %q, %t)", tc.in, impPath, pkg, ok, tc.impPath, tc.pkg, tc.ok) } } } yarpc-0.0.1/cmd/protoc-gen-yarpc/main.go000066400000000000000000000011001331225777200200360ustar00rootroot00000000000000package main import ( "github.com/gogo/protobuf/vanity/command" "github.com/influxdata/yarpc/cmd/protoc-gen-yarpc/generator" "github.com/influxdata/yarpc/cmd/protoc-gen-yarpc/yarpc" ) func main() { g := generator.New() g.Request = command.Read() g.Suffix = ".yarpc.go" g.CommandLineParameters(g.Request.GetParameter()) // Create a wrapped version of the Descriptors and EnumDescriptors that // point to the file that defines them. g.WrapTypes() g.SetPackageNames() g.BuildTypeNameMap() p := &yarpc.Plugin{} g.GeneratePlugin(p) command.Write(g.Response) } yarpc-0.0.1/cmd/protoc-gen-yarpc/yarpc/000077500000000000000000000000001331225777200177115ustar00rootroot00000000000000yarpc-0.0.1/cmd/protoc-gen-yarpc/yarpc/plugin.go000066400000000000000000000375101331225777200215440ustar00rootroot00000000000000// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Package yarpc outputs yarpc service descriptions in Go code. // It runs as a plugin for the Go protocol buffer compiler plugin. // It is linked in to protoc-gen-yarpc. package yarpc import ( "fmt" "path" "strconv" "strings" pb "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" "github.com/influxdata/yarpc/cmd/protoc-gen-yarpc/generator" "github.com/influxdata/yarpc/yarpcproto" ) // generatedCodeVersion indicates a version of the generated code. // It is incremented whenever an incompatibility between the generated code and // the yarpc package is introduced; the generated code references // a constant, yarpc.SupportPackageIsVersionN (where N is generatedCodeVersion). const generatedCodeVersion = 1 // Paths for packages used by code generated in this file, // relative to the import_prefix of the generator.Generator. const ( contextPkgPath = "context" yarpcPkgPath = "github.com/influxdata/yarpc" ) // yarpc is an implementation of the Go protocol buffer compiler's // plugin architecture. It generates bindings for yarpc support. type Plugin struct { gen *generator.Generator } var _ generator.Plugin = (*Plugin)(nil) // Name returns the name of this plugin, "yarpc". func (g *Plugin) Name() string { return "yarpc" } // The names for packages imported in the generated code. // They may vary from the final path component of the import path // if the name is used by other packages. var ( contextPkg string yarpcPkg string ) // Init initializes the plugin. func (g *Plugin) Init(gen *generator.Generator) { g.gen = gen contextPkg = generator.RegisterUniquePackageName("context", nil) yarpcPkg = generator.RegisterUniquePackageName("yarpc", nil) } // Given a type name defined in a .proto, return its object. // Also record that we're using it, to guarantee the associated import. func (g *Plugin) objectNamed(name string) generator.Object { g.gen.RecordTypeUse(name) return g.gen.ObjectNamed(name) } // Given a type name defined in a .proto, return its name as we will print it. func (g *Plugin) typeName(str string) string { return g.gen.TypeName(g.objectNamed(str)) } // P forwards to g.gen.P. func (g *Plugin) P(args ...interface{}) { g.gen.P(args...) } // Generate generates code for the services in the given file. func (g *Plugin) Generate(file *generator.FileDescriptor) { if len(file.FileDescriptorProto.Service) == 0 { return } g.P("// Reference imports to suppress errors if they are not otherwise used.") g.P("var _ ", contextPkg, ".Context") g.P("var _ ", yarpcPkg, ".ClientConn") g.P() // Assert version compatibility. g.P("// This is a compile-time assertion to ensure that this generated file") g.P("// is compatible with the yarpc package it is being compiled against.") g.P("const _ = ", yarpcPkg, ".SupportPackageIsVersion", generatedCodeVersion) g.P() for i, service := range file.FileDescriptorProto.Service { g.generateService(file, service, i) } } // GenerateImports generates the import declaration for this file. func (g *Plugin) GenerateImports(file *generator.FileDescriptor) { if len(file.FileDescriptorProto.Service) == 0 { return } g.P("import (") g.P(contextPkg, " ", strconv.Quote(path.Join(g.gen.ImportPrefix, contextPkgPath))) g.P(yarpcPkg, " ", strconv.Quote(path.Join(g.gen.ImportPrefix, yarpcPkgPath))) g.P(")") g.P() } // reservedClientName records whether a client name is reserved on the client side. var reservedClientName = map[string]bool{ // TODO: do we need any in yarpc? } func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] } func (g *Plugin) getServiceIndex(service *pb.ServiceDescriptorProto) int { idx := yarpcproto.GetServiceIndex(service) if idx == -1 { g.gen.Error(fmt.Errorf("service %s missing yarpc_service_index option", service.GetName())) } if idx > 0xff { g.gen.Error(fmt.Errorf("service %s has invalid yarpc_service_index %d; must be less than 256", service.GetName(), idx)) } return idx } func (g *Plugin) getMethodIndex(service *pb.ServiceDescriptorProto, method *pb.MethodDescriptorProto) int { idx := yarpcproto.GetMethodIndex(method) if idx == -1 { g.gen.Error(fmt.Errorf("method %s.%s missing yarpc_method_index option", service.GetName(), method.GetName())) } if idx > 0xff { g.gen.Error(fmt.Errorf("method %s.%s has invalid yarpc_method_index %d; must be less than 256", service.GetName(), method.GetName(), idx)) } return idx } // generateService generates all the code for the named service. func (g *Plugin) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) { cpath := fmt.Sprintf("6,%d", index) // 6 means service. origServName := service.GetName() fullServName := origServName if pkg := file.GetPackage(); pkg != "" { fullServName = pkg + "." + fullServName } servName := generator.CamelCase(origServName) g.P() g.P("// Client API for ", servName, " service") g.P() // Client interface. g.P("type ", servName, "Client interface {") for i, method := range service.Method { g.gen.PrintComments(fmt.Sprintf("%s,2,%d", cpath, i)) // 2 means method in a service. g.P(g.generateClientSignature(servName, method)) } g.P("}") g.P() // Client structure. g.P("type ", unexport(servName), "Client struct {") g.P("cc *", yarpcPkg, ".ClientConn") g.P("}") g.P() // NewClient factory. g.P("func New", servName, "Client (cc *", yarpcPkg, ".ClientConn) ", servName, "Client {") g.P("return &", unexport(servName), "Client{cc}") g.P("}") g.P() var methodIndex, streamIndex int serviceDescVar := "_" + servName + "_serviceDesc" // Client method implementations. for _, method := range service.Method { sidx := g.getServiceIndex(service) midx := g.getMethodIndex(service, method) var descExpr string if !method.GetServerStreaming() && !method.GetClientStreaming() { // Unary RPC method descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex) methodIndex++ } else { // Streaming RPC method descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex) streamIndex++ } api := ((sidx << 8) | midx) & 0xffff g.generateClientMethod(servName, api, serviceDescVar, method, descExpr) } g.P("// Server API for ", servName, " service") g.P() // Server interface. serverType := servName + "Server" g.P("type ", serverType, " interface {") for i, method := range service.Method { g.gen.PrintComments(fmt.Sprintf("%s,2,%d", cpath, i)) // 2 means method in a service. g.P(g.generateServerSignature(servName, method)) } g.P("}") g.P() // Server registration. g.P("func Register", servName, "Server(s *", yarpcPkg, ".Server, srv ", serverType, ") {") g.P("s.RegisterService(&", serviceDescVar, `, srv)`) g.P("}") g.P() // Server handler implementations. var handlerNames []string for _, method := range service.Method { hname := g.generateServerMethod(servName, fullServName, method) handlerNames = append(handlerNames, hname) } sidx := g.getServiceIndex(service) // Service descriptor. g.P("var ", serviceDescVar, " = ", yarpcPkg, ".ServiceDesc {") g.P("ServiceName: ", strconv.Quote(fullServName), ",") g.P("Index: ", sidx, ",") g.P("HandlerType: (*", serverType, ")(nil),") g.P("Methods: []", yarpcPkg, ".MethodDesc{") for i, method := range service.Method { if method.GetServerStreaming() || method.GetClientStreaming() { continue } midx := g.getMethodIndex(service, method) g.P("{") g.P("MethodName: ", strconv.Quote(method.GetName()), ",") g.P("Index: ", midx, ",") g.P("Handler: ", handlerNames[i], ",") g.P("},") } g.P("},") g.P("Streams: []", yarpcPkg, ".StreamDesc{") for i, method := range service.Method { if !method.GetServerStreaming() && !method.GetClientStreaming() { continue } midx := g.getMethodIndex(service, method) g.P("{") g.P("StreamName: ", strconv.Quote(method.GetName()), ",") g.P("Index: ", midx, ",") g.P("Handler: ", handlerNames[i], ",") if method.GetServerStreaming() { g.P("ServerStreams: true,") } if method.GetClientStreaming() { g.P("ClientStreams: true,") } g.P("},") } g.P("},") g.P("Metadata: \"", file.GetName(), "\",") g.P("}") g.P() } // generateClientSignature returns the client-side signature for a method. func (g *Plugin) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string { origMethName := method.GetName() methName := generator.CamelCase(origMethName) if reservedClientName[methName] { methName += "_" } reqArg := ", in *" + g.typeName(method.GetInputType()) if method.GetClientStreaming() { reqArg = "" } respName := "*" + g.typeName(method.GetOutputType()) if method.GetServerStreaming() || method.GetClientStreaming() { respName = servName + "_" + generator.CamelCase(origMethName) + "Client" } return fmt.Sprintf("%s(ctx %s.Context%s) (%s, error)", methName, contextPkg, reqArg, respName) } func (g *Plugin) generateClientMethod(servName string, api int, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) { apihex := fmt.Sprintf("0x%04x", api) methName := generator.CamelCase(method.GetName()) inType := g.typeName(method.GetInputType()) outType := g.typeName(method.GetOutputType()) g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{") if !method.GetServerStreaming() && !method.GetClientStreaming() { g.P("out := new(", outType, ")") // TODO: Pass descExpr to Invoke. g.P("err := ", yarpcPkg, `.Invoke(ctx, `, apihex, `, in, out, c.cc)`) g.P("if err != nil { return nil, err }") g.P("return out, nil") g.P("}") g.P() return } streamType := unexport(servName) + methName + "Client" g.P("stream, err := ", yarpcPkg, ".NewClientStream(ctx, ", descExpr, `, c.cc, `, apihex, `)`) g.P("if err != nil { return nil, err }") g.P("x := &", streamType, "{stream}") if !method.GetClientStreaming() { g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }") //g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") } g.P("return x, nil") g.P("}") g.P() genSend := method.GetClientStreaming() genRecv := method.GetServerStreaming() genCloseAndRecv := !method.GetServerStreaming() // Stream auxiliary types and methods. g.P("type ", servName, "_", methName, "Client interface {") if genSend { g.P("Send(*", inType, ") error") } if genRecv { g.P("Recv() (*", outType, ", error)") } if genCloseAndRecv { g.P("CloseAndRecv() (*", outType, ", error)") } g.P(yarpcPkg, ".ClientStream") g.P("}") g.P() g.P("type ", streamType, " struct {") g.P(yarpcPkg, ".ClientStream") g.P("}") g.P() if genSend { g.P("func (x *", streamType, ") Send(m *", inType, ") error {") g.P("return x.ClientStream.SendMsg(m)") g.P("}") g.P() } if genRecv { g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {") g.P("m := new(", outType, ")") g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } if genCloseAndRecv { g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {") g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") g.P("m := new(", outType, ")") g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } } // generateServerSignature returns the server-side signature for a method. func (g *Plugin) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string { origMethName := method.GetName() methName := generator.CamelCase(origMethName) if reservedClientName[methName] { methName += "_" } var reqArgs []string ret := "error" if !method.GetServerStreaming() && !method.GetClientStreaming() { reqArgs = append(reqArgs, contextPkg+".Context") ret = "(*" + g.typeName(method.GetOutputType()) + ", error)" } if !method.GetClientStreaming() { reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType())) } if method.GetServerStreaming() || method.GetClientStreaming() { reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server") } return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret } func (g *Plugin) generateServerMethod(servName, fullServName string, method *pb.MethodDescriptorProto) string { methName := generator.CamelCase(method.GetName()) hname := fmt.Sprintf("_%s_%s_Handler", servName, methName) inType := g.typeName(method.GetInputType()) outType := g.typeName(method.GetOutputType()) if !method.GetServerStreaming() && !method.GetClientStreaming() { g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, dec func(interface{}) error) (interface{}, error) {") g.P("in := new(", inType, ")") g.P("if err := dec(in); err != nil { return nil, err }") g.P("return srv.(", servName, "Server).", methName, "(ctx, in)") g.P("}") g.P() return hname } streamType := unexport(servName) + methName + "Server" g.P("func ", hname, "(srv interface{}, stream ", yarpcPkg, ".ServerStream) error {") if !method.GetClientStreaming() { g.P("m := new(", inType, ")") g.P("if err := stream.RecvMsg(m); err != nil { return err }") g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})") } else { g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})") } g.P("}") g.P() genSend := method.GetServerStreaming() genSendAndClose := !method.GetServerStreaming() genRecv := method.GetClientStreaming() // Stream auxiliary types and methods. g.P("type ", servName, "_", methName, "Server interface {") if genSend { g.P("Send(*", outType, ") error") } if genSendAndClose { g.P("SendAndClose(*", outType, ") error") } if genRecv { g.P("Recv() (*", inType, ", error)") } g.P(yarpcPkg, ".ServerStream") g.P("}") g.P() g.P("type ", streamType, " struct {") g.P(yarpcPkg, ".ServerStream") g.P("}") g.P() if genSend { g.P("func (x *", streamType, ") Send(m *", outType, ") error {") g.P("return x.ServerStream.SendMsg(m)") g.P("}") g.P() } if genSendAndClose { g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {") g.P("return x.ServerStream.SendMsg(m)") g.P("}") g.P() } if genRecv { g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {") g.P("m := new(", inType, ")") g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } return hname } yarpc-0.0.1/codec.go000066400000000000000000000042731331225777200142510ustar00rootroot00000000000000package yarpc import ( "encoding/binary" "io" "sync" "github.com/gogo/protobuf/codec" "github.com/influxdata/yamux" "github.com/influxdata/yarpc/codes" "github.com/influxdata/yarpc/status" ) var ( codecPool = &sync.Pool{ New: func() interface{} { return codec.New(1024) }, } ) type pooledCodec struct{} var ( cd = &pooledCodec{} ) func NewCodec() Codec { return cd } func (*pooledCodec) Marshal(v interface{}) ([]byte, error) { ci := codecPool.Get() c := ci.(codec.Codec) data, err := c.Marshal(v) // To avoid a data race, create a copy of data before we return the codec to the pool. dataCopy := append([]byte(nil), data...) codecPool.Put(ci) return dataCopy, err } func (*pooledCodec) Unmarshal(data []byte, v interface{}) error { ci := codecPool.Get() c := ci.(codec.Codec) err := c.Unmarshal(data, v) codecPool.Put(ci) return err } type Codec interface { Marshal(v interface{}) ([]byte, error) Unmarshal(data []byte, v interface{}) error } type parser struct { r io.Reader header [4]byte } func (p *parser) recvMsg() (msg []byte, err error) { if _, err := io.ReadFull(p.r, p.header[:]); err != nil { return nil, err } length := binary.BigEndian.Uint32(p.header[:]) if length == 0 { return nil, nil } msg = make([]byte, int(length)) if _, err := io.ReadFull(p.r, msg); err != nil { if err == io.EOF { err = io.ErrUnexpectedEOF } return nil, err } return msg, nil } func encode(c Codec, msg interface{}) ([]byte, error) { var ( b []byte length uint ) if msg != nil { var err error b, err = c.Marshal(msg) if err != nil { // TODO(sgc): should return error with status code "internal" return nil, status.Errorf(codes.Internal, "rpc: error while marshaling %v", err) } length = uint(len(b)) } const ( sizeLen = 4 ) var buf = make([]byte, sizeLen+length) binary.BigEndian.PutUint32(buf, uint32(length)) copy(buf[4:], b) return buf, nil } func decode(p *parser, c Codec, s *yamux.Stream, m interface{}) error { d, err := p.recvMsg() if err != nil { return err } if err := c.Unmarshal(d, m); err != nil { return status.Errorf(codes.Internal, "rpc: failed to unmarshal received message %v", err) } return nil } yarpc-0.0.1/codes/000077500000000000000000000000001331225777200137345ustar00rootroot00000000000000yarpc-0.0.1/codes/codes.pb.go000066400000000000000000000061611331225777200157640ustar00rootroot00000000000000// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: codes/codes.proto /* Package codes is a generated protocol buffer package. It is generated from these files: codes/codes.proto It has these top-level messages: */ package codes import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type Code int32 const ( // OK is returned on success. OK Code = 0 // Unknown error. Unknown Code = 1 // Unimplemented indicates operation is not implemented or not // supported/enabled in this service. Unimplemented Code = 2 // Internal errors. Means some invariants expected by underlying // system has been broken. If you see one of these errors, // something is very broken. Internal Code = 3 ) var Code_name = map[int32]string{ 0: "OK", 1: "UNKNOWN", 2: "UNIMPLEMETED", 3: "INTERNAL", } var Code_value = map[string]int32{ "OK": 0, "UNKNOWN": 1, "UNIMPLEMETED": 2, "INTERNAL": 3, } func (x Code) String() string { return proto.EnumName(Code_name, int32(x)) } func (Code) EnumDescriptor() ([]byte, []int) { return fileDescriptorCodes, []int{0} } func init() { proto.RegisterEnum("codes.Code", Code_name, Code_value) } func init() { proto.RegisterFile("codes/codes.proto", fileDescriptorCodes) } var fileDescriptorCodes = []byte{ // 219 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4c, 0xce, 0x4f, 0x49, 0x2d, 0xd6, 0x07, 0x93, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0xac, 0x60, 0x8e, 0x94, 0x6e, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x7a, 0xbe, 0x3e, 0x58, 0x36, 0xa9, 0x34, 0x0d, 0xcc, 0x03, 0x73, 0xc0, 0x2c, 0x88, 0x2e, 0xad, 0x72, 0x2e, 0x16, 0xe7, 0xfc, 0x94, 0x54, 0x21, 0x3e, 0x2e, 0x26, 0x7f, 0x6f, 0x01, 0x06, 0x29, 0xb6, 0xae, 0xb9, 0x0a, 0x4c, 0xfe, 0xde, 0x42, 0x12, 0x5c, 0xec, 0xa1, 0x7e, 0xde, 0x7e, 0xfe, 0xe1, 0x7e, 0x02, 0x8c, 0x52, 0xdc, 0x5d, 0x73, 0x15, 0xd8, 0x43, 0xf3, 0xb2, 0xf3, 0xf2, 0xcb, 0xf3, 0x84, 0x94, 0xb9, 0x78, 0x42, 0xfd, 0x3c, 0x7d, 0x03, 0x7c, 0x5c, 0x7d, 0x5d, 0x43, 0x5c, 0x5d, 0x04, 0x98, 0xa4, 0x04, 0xbb, 0xe6, 0x2a, 0xf0, 0x86, 0xe6, 0x65, 0xe6, 0x16, 0xe4, 0xa4, 0xe6, 0xa6, 0xe6, 0x95, 0xa4, 0xa6, 0x08, 0x49, 0x71, 0x71, 0x78, 0xfa, 0x85, 0xb8, 0x06, 0xf9, 0x39, 0xfa, 0x08, 0x30, 0x4b, 0xf1, 0x74, 0xcd, 0x55, 0xe0, 0xf0, 0xcc, 0x2b, 0x49, 0x2d, 0xca, 0x4b, 0xcc, 0x91, 0x62, 0xe9, 0x58, 0x2c, 0xc7, 0xe0, 0x24, 0x70, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f, 0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x90, 0xc4, 0x06, 0x76, 0x91, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xd4, 0x54, 0x67, 0x0c, 0xdc, 0x00, 0x00, 0x00, } yarpc-0.0.1/codes/codes.proto000066400000000000000000000013311331225777200161140ustar00rootroot00000000000000syntax = "proto3"; package codes; import "github.com/gogo/protobuf/gogoproto/gogo.proto"; enum Code { option (gogoproto.goproto_enum_prefix) = false; // OK is returned on success. OK = 0 [(gogoproto.enumvalue_customname) = "OK"]; // Unknown error. UNKNOWN = 1 [(gogoproto.enumvalue_customname) = "Unknown"]; // Unimplemented indicates operation is not implemented or not // supported/enabled in this service. UNIMPLEMETED = 2 [(gogoproto.enumvalue_customname) = "Unimplemented"]; // Internal errors. Means some invariants expected by underlying // system has been broken. If you see one of these errors, // something is very broken. INTERNAL = 3 [(gogoproto.enumvalue_customname) = "Internal"]; } yarpc-0.0.1/rpc.go000066400000000000000000000005741331225777200137600ustar00rootroot00000000000000package yarpc //go:generate protoc -I$GOPATH/src -I. --gogofaster_out=. codes/codes.proto //go:generate protoc -I$GOPATH/src -I. --gogofaster_out=. status/status.proto //go:generate protoc -I$GOPATH/src -I. --gogofaster_out=Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor:. yarpcproto/yarpc.proto const ( SupportPackageIsVersion1 = true ) yarpc-0.0.1/server.go000066400000000000000000000146131331225777200145010ustar00rootroot00000000000000package yarpc import ( "net" "sync" "encoding/binary" "io" "context" "reflect" "log" "github.com/influxdata/yamux" "github.com/influxdata/yarpc/codes" "github.com/influxdata/yarpc/status" ) type methodHandler func(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) type MethodDesc struct { Index uint8 MethodName string Handler methodHandler } // ServiceDesc represents an RPC service's specification. type ServiceDesc struct { Index uint8 ServiceName string // The pointer to the service interface. Used to check whether the user // provided implementation satisfies the interface requirements. HandlerType interface{} Methods []MethodDesc Streams []StreamDesc Metadata interface{} } type service struct { server interface{} md map[uint8]*MethodDesc sd map[uint8]*StreamDesc } type Server struct { opts options m map[uint8]*service serve bool lis net.Listener lisMu sync.Mutex } type options struct { codec Codec } type ServerOption func(*options) func CustomCodec(c Codec) ServerOption { return func(o *options) { o.codec = c } } func NewServer(opts ...ServerOption) *Server { s := &Server{ m: make(map[uint8]*service), } for _, opt := range opts { opt(&s.opts) } // defaults if s.opts.codec == nil { s.opts.codec = NewCodec() } return s } // RegisterService registers a service and its implementation to the gRPC // server. It is called from the IDL generated code. This must be called before // invoking Serve. func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) { ht := reflect.TypeOf(sd.HandlerType).Elem() st := reflect.TypeOf(ss) if !st.Implements(ht) { log.Fatalf("rpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht) } s.register(sd, ss) } func (s *Server) register(sd *ServiceDesc, ss interface{}) { // s.opts.log.Info("register service", zap.String("name", sd.ServiceName), zap.Uint("index", uint(sd.Index))) if s.serve { log.Fatalf("rpc: Server.RegisterService after Server.Serve for %q", sd.ServiceName) } if _, ok := s.m[sd.Index]; ok { log.Fatalf("rpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName) } srv := &service{ server: ss, md: make(map[uint8]*MethodDesc), sd: make(map[uint8]*StreamDesc), } for i := range sd.Methods { d := &sd.Methods[i] srv.md[d.Index] = d } for i := range sd.Streams { d := &sd.Streams[i] srv.sd[d.Index] = d } s.m[sd.Index] = srv } func (s *Server) Serve(lis net.Listener) error { s.lisMu.Lock() s.lis = lis s.lisMu.Unlock() for { rawConn, err := lis.Accept() if err != nil { if ne, ok := err.(interface { Temporary() bool }); ok && ne.Temporary() { // TODO(sgc): add logic to handle temporary errors } return err } go s.handleRawConn(rawConn) } } func (s *Server) Stop() { s.lisMu.Lock() defer s.lisMu.Unlock() if s.lis != nil { s.lis.Close() s.lis = nil } } func (s *Server) handleRawConn(rawConn net.Conn) { session, err := yamux.Server(rawConn, nil) if err != nil { log.Printf("ERR yamux.Server failed: error=%v", err) rawConn.Close() return } s.serveSession(session) } func (s *Server) serveSession(session *yamux.Session) { for { stream, err := session.AcceptStream() if err != nil { if err != io.EOF { // TODO(sgc): handle session errors log.Printf("ERR session.AcceptStream failed: error=%v", err) session.Close() } return } go s.handleStream(stream) } } func decodeServiceMethod(v uint16) (svc, mth uint8) { //┌────────────────────────┬────────────────────────┐ //│ SERVICE (8) │ METHOD (8) │ //└────────────────────────┴────────────────────────┘ return uint8(v >> 8), uint8(v) } func (s *Server) handleStream(st *yamux.Stream) { defer st.Close() var tmp [2]byte io.ReadAtLeast(st, tmp[:], 2) service, method := decodeServiceMethod(binary.BigEndian.Uint16(tmp[:])) srv, ok := s.m[service] if !ok { // TODO(sgc): handle unknown service log.Printf("invalid service identifier: service=%d", service) return } if md, ok := srv.md[method]; ok { // handle unary s.handleUnaryRPC(st, srv, md) return } if sd, ok := srv.sd[method]; ok { // handle unary s.handleStreamingRPC(st, srv, sd) return } // TODO(sgc): handle unknown method log.Printf("ERR invalid method identifier: service=%d method=%d", service, method) } func (s *Server) handleStreamingRPC(st *yamux.Stream, srv *service, sd *StreamDesc) { ss := &serverStream{ cn: st, codec: s.opts.codec, p: &parser{r: st}, } var appErr error var server interface{} if srv != nil { server = srv.server } appErr = sd.Handler(server, ss) if appErr != nil { // TODO(sgc): handle app error using similar code style to gRPC log.Printf("ERR sd.Handler failed: error=%v", appErr) // appStatus, ok := status.FromError(appErr) return } // TODO(sgc): write OK status? } func (s *Server) handleUnaryRPC(st *yamux.Stream, srv *service, md *MethodDesc) error { p := &parser{r: st} req, err := p.recvMsg() if err == io.EOF { return err } if err == io.ErrUnexpectedEOF { return status.Errorf(codes.Internal, err.Error()) } df := func(v interface{}) error { if err := s.opts.codec.Unmarshal(req, v); err != nil { return status.Errorf(codes.Internal, "rpc: error unmarshalling request: %v", err) } return nil } reply, appErr := md.Handler(srv.server, context.Background(), df) if appErr != nil { appStatus, ok := status.FromError(appErr) if !ok { // convert to app error appStatus = &status.Status{Code: codes.Unknown, Message: appErr.Error()} appErr = appStatus } // TODO(sgc): write error status return appErr } if err := s.sendResponse(st, reply); err != nil { if err == io.EOF { return err } if s, ok := status.FromError(err); ok { // TODO(sgc): write error status _ = s } return err } // TODO(sgc): write OK status return nil } func (s *Server) sendResponse(stream *yamux.Stream, msg interface{}) error { buf, err := encode(s.opts.codec, msg) if err != nil { // s.opts.log.Error("rpc: server failed to encode reply", zap.Error(err)) return err } _, err = stream.Write(buf) return err } yarpc-0.0.1/status/000077500000000000000000000000001331225777200141625ustar00rootroot00000000000000yarpc-0.0.1/status/status.go000066400000000000000000000012401331225777200160310ustar00rootroot00000000000000package status import ( "fmt" "github.com/influxdata/yarpc/codes" ) func (m *Status) Error() string { return fmt.Sprintf("rpc error: code = %s desc = %s", m.Code, m.Message) } // FromError returns a Status representing err if it was produced from this // package, otherwise it returns nil, false. func FromError(err error) (s *Status, ok bool) { if err == nil { return &Status{Code: codes.OK}, true } if s, ok := err.(*Status); ok { return s, true } return nil, false } // Errorf returns Error(c, fmt.Sprintf(format, a...)). func Errorf(c codes.Code, format string, a ...interface{}) error { return &Status{Code: c, Message: fmt.Sprintf(format, a...)} } yarpc-0.0.1/status/status.pb.go000066400000000000000000000210221331225777200164310ustar00rootroot00000000000000// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: status/status.proto /* Package status is a generated protocol buffer package. It is generated from these files: status/status.proto It has these top-level messages: Status */ package status import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/gogo/protobuf/gogoproto" import codes "github.com/influxdata/yarpc/codes" import io "io" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type Status struct { Code codes.Code `protobuf:"varint,1,opt,name=code,proto3,enum=codes.Code" json:"code,omitempty"` Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` } func (m *Status) Reset() { *m = Status{} } func (m *Status) String() string { return proto.CompactTextString(m) } func (*Status) ProtoMessage() {} func (*Status) Descriptor() ([]byte, []int) { return fileDescriptorStatus, []int{0} } func (m *Status) GetCode() codes.Code { if m != nil { return m.Code } return codes.OK } func (m *Status) GetMessage() string { if m != nil { return m.Message } return "" } func init() { proto.RegisterType((*Status)(nil), "status.Status") } func (m *Status) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *Status) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l if m.Code != 0 { dAtA[i] = 0x8 i++ i = encodeVarintStatus(dAtA, i, uint64(m.Code)) } if len(m.Message) > 0 { dAtA[i] = 0x12 i++ i = encodeVarintStatus(dAtA, i, uint64(len(m.Message))) i += copy(dAtA[i:], m.Message) } return i, nil } func encodeFixed64Status(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) dAtA[offset+1] = uint8(v >> 8) dAtA[offset+2] = uint8(v >> 16) dAtA[offset+3] = uint8(v >> 24) dAtA[offset+4] = uint8(v >> 32) dAtA[offset+5] = uint8(v >> 40) dAtA[offset+6] = uint8(v >> 48) dAtA[offset+7] = uint8(v >> 56) return offset + 8 } func encodeFixed32Status(dAtA []byte, offset int, v uint32) int { dAtA[offset] = uint8(v) dAtA[offset+1] = uint8(v >> 8) dAtA[offset+2] = uint8(v >> 16) dAtA[offset+3] = uint8(v >> 24) return offset + 4 } func encodeVarintStatus(dAtA []byte, offset int, v uint64) int { for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } dAtA[offset] = uint8(v) return offset + 1 } func (m *Status) Size() (n int) { var l int _ = l if m.Code != 0 { n += 1 + sovStatus(uint64(m.Code)) } l = len(m.Message) if l > 0 { n += 1 + l + sovStatus(uint64(l)) } return n } func sovStatus(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozStatus(x uint64) (n int) { return sovStatus(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *Status) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowStatus } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: Status: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: Status: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType) } m.Code = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowStatus } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ m.Code |= (codes.Code(b) & 0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Message", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowStatus } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthStatus } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.Message = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipStatus(dAtA[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthStatus } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipStatus(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowStatus } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowStatus } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if dAtA[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowStatus } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } iNdEx += length if length < 0 { return 0, ErrInvalidLengthStatus } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowStatus } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipStatus(dAtA[start:]) if err != nil { return 0, err } iNdEx = start + next } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") } var ( ErrInvalidLengthStatus = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowStatus = fmt.Errorf("proto: integer overflow") ) func init() { proto.RegisterFile("status/status.proto", fileDescriptorStatus) } var fileDescriptorStatus = []byte{ // 177 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2e, 0x2e, 0x49, 0x2c, 0x29, 0x2d, 0xd6, 0x87, 0x50, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0x6c, 0x10, 0x9e, 0x94, 0x6e, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x7a, 0xbe, 0x3e, 0x58, 0x3a, 0xa9, 0x34, 0x0d, 0xcc, 0x03, 0x73, 0xc0, 0x2c, 0x88, 0x36, 0x14, 0xe5, 0x99, 0x79, 0x69, 0x39, 0xa5, 0x15, 0x29, 0x89, 0x25, 0x89, 0xfa, 0x95, 0x89, 0x45, 0x05, 0xc9, 0xfa, 0xc9, 0xf9, 0x29, 0xa9, 0xc5, 0x10, 0x12, 0xa2, 0x5c, 0xc9, 0x99, 0x8b, 0x2d, 0x18, 0x6c, 0x8f, 0x90, 0x3c, 0x17, 0x0b, 0x48, 0x42, 0x82, 0x51, 0x81, 0x51, 0x83, 0xcf, 0x88, 0x5b, 0x0f, 0xa2, 0xca, 0x39, 0x3f, 0x25, 0x35, 0x08, 0x2c, 0x21, 0x24, 0xc1, 0xc5, 0x9e, 0x9b, 0x5a, 0x5c, 0x9c, 0x98, 0x9e, 0x2a, 0xc1, 0xa4, 0xc0, 0xa8, 0xc1, 0x19, 0x04, 0xe3, 0x3a, 0x09, 0x9c, 0x78, 0x24, 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x24, 0xb1, 0x81, 0x4d, 0x37, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0x8c, 0xec, 0x25, 0x86, 0xda, 0x00, 0x00, 0x00, } yarpc-0.0.1/status/status.proto000066400000000000000000000003251331225777200165720ustar00rootroot00000000000000syntax = "proto3"; package status; import "github.com/gogo/protobuf/gogoproto/gogo.proto"; import "github.com/influxdata/yarpc/codes/codes.proto"; message Status { codes.Code code = 1; string message = 2; } yarpc-0.0.1/stream.go000066400000000000000000000100041331225777200144540ustar00rootroot00000000000000package yarpc import ( "context" "encoding/binary" "errors" "io" "github.com/influxdata/yamux" "github.com/influxdata/yarpc/codes" "github.com/influxdata/yarpc/status" ) type StreamHandler func(srv interface{}, stream ServerStream) error type StreamDesc struct { Index uint8 StreamName string Handler StreamHandler ServerStreams bool ClientStreams bool } // Stream defines the common interface a client or server stream has to satisfy. type Stream interface { // Context returns the context for this stream. Context() context.Context // SendMsg blocks until it sends m, the stream is done or the stream // breaks. // On error, it aborts the stream and returns an RPC status on client // side. On server side, it simply returns the error to the caller. // SendMsg is called by generated code. Also Users can call SendMsg // directly when it is really needed in their use cases. // It's safe to have a goroutine calling SendMsg and another goroutine calling // recvMsg on the same stream at the same time. // But it is not safe to call SendMsg on the same stream in different goroutines. SendMsg(m interface{}) error // RecvMsg blocks until it receives a message or the stream is // done. On client side, it returns io.EOF when the stream is done. On // any other error, it aborts the stream and returns an RPC status. On // server side, it simply returns the error to the caller. // It's safe to have a goroutine calling SendMsg and another goroutine calling // recvMsg on the same stream at the same time. // But it is not safe to call RecvMsg on the same stream in different goroutines. RecvMsg(m interface{}) error } // ClientStream defines the interface a client stream has to satisfy. type ClientStream interface { // CloseSend closes the send direction of the stream. It closes the stream // when non-nil error is met. CloseSend() error Stream } func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, api uint16) (ClientStream, error) { cn, err := cc.NewStream() if err != nil { return nil, err } var tmp [2]byte binary.BigEndian.PutUint16(tmp[:], api) _, err = cn.Write(tmp[:]) if err != nil { return nil, err } cs := &clientStream{ cn: cn, codec: cc.dopts.codec, p: &parser{r: cn}, desc: desc, ctx: ctx, closing: make(chan struct{}), } go func() { select { case <-ctx.Done(): cs.CloseSend() case <-cs.closing: } }() return cs, nil } type clientStream struct { cn *yamux.Stream codec Codec p *parser desc *StreamDesc ctx context.Context closing chan struct{} } func (c *clientStream) CloseSend() error { select { case <-c.closing: default: close(c.closing) } return c.cn.Close() } func (c *clientStream) Context() context.Context { return c.ctx } func (c *clientStream) SendMsg(m interface{}) error { select { case <-c.closing: return errors.New("stream closed") default: } out, err := encode(c.codec, m) if err != nil { return err } _, err = c.cn.Write(out) return err } func (c *clientStream) RecvMsg(m interface{}) error { select { case <-c.closing: return errors.New("stream closed") default: } err := decode(c.p, c.codec, c.cn, m) if err == nil { if !c.desc.ClientStreams || c.desc.ServerStreams { return nil } } return err } type ServerStream interface { Stream } type serverStream struct { cn *yamux.Stream codec Codec p *parser buf []byte } func (s *serverStream) Context() context.Context { panic("implement me") } func (s *serverStream) SendMsg(m interface{}) error { out, err := encode(s.codec, m) if err != nil { return err } _, err = s.cn.Write(out) if err != nil { // TODO(sgc): wrap in status error return err } return nil } func (s *serverStream) RecvMsg(m interface{}) error { if err := decode(s.p, s.codec, s.cn, m); err != nil { if err == io.EOF { return err } if err == io.ErrUnexpectedEOF { err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error()) } // TODO(sgc): wrap in status error return err } return nil } yarpc-0.0.1/test/000077500000000000000000000000001331225777200136165ustar00rootroot00000000000000yarpc-0.0.1/test/foo/000077500000000000000000000000001331225777200144015ustar00rootroot00000000000000yarpc-0.0.1/test/foo/foo.go000066400000000000000000000010121331225777200155050ustar00rootroot00000000000000package foo type fooCodec struct { } func (fooCodec) Marshal(v interface{}) ([]byte, error) { switch t := v.(type) { case *Request: return []byte(t.In), nil case *Response: return []byte(t.Out), nil default: panic("invalid type") } } func (fooCodec) Unmarshal(data []byte, v interface{}) error { str := string(data) switch t := v.(type) { case *Request: t.In = str case *Response: t.Out = str default: panic("invalid type") } return nil } func (fooCodec) String() string { return "FooCodec" } yarpc-0.0.1/test/foo/foo.pb.go000066400000000000000000000063521331225777200161210ustar00rootroot00000000000000// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: test/foo/foo.proto /* Package foo is a generated protocol buffer package. It is generated from these files: test/foo/foo.proto It has these top-level messages: Request Response */ package foo import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/influxdata/yarpc/yarpcproto" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package type Request struct { In string `protobuf:"bytes,1,opt,name=in,proto3" json:"in,omitempty"` } func (m *Request) Reset() { *m = Request{} } func (m *Request) String() string { return proto.CompactTextString(m) } func (*Request) ProtoMessage() {} func (*Request) Descriptor() ([]byte, []int) { return fileDescriptorFoo, []int{0} } func (m *Request) GetIn() string { if m != nil { return m.In } return "" } type Response struct { Out string `protobuf:"bytes,1,opt,name=out,proto3" json:"out,omitempty"` } func (m *Response) Reset() { *m = Response{} } func (m *Response) String() string { return proto.CompactTextString(m) } func (*Response) ProtoMessage() {} func (*Response) Descriptor() ([]byte, []int) { return fileDescriptorFoo, []int{1} } func (m *Response) GetOut() string { if m != nil { return m.Out } return "" } func init() { proto.RegisterType((*Request)(nil), "foo.Request") proto.RegisterType((*Response)(nil), "foo.Response") } func init() { proto.RegisterFile("test/foo/foo.proto", fileDescriptorFoo) } var fileDescriptorFoo = []byte{ // 206 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2a, 0x49, 0x2d, 0x2e, 0xd1, 0x4f, 0xcb, 0xcf, 0x07, 0x61, 0xbd, 0x82, 0xa2, 0xfc, 0x92, 0x7c, 0x21, 0xe6, 0xb4, 0xfc, 0x7c, 0x29, 0x93, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0xfd, 0xe2, 0x92, 0xd2, 0xc4, 0xa2, 0x92, 0xe4, 0xc4, 0xa2, 0xbc, 0xcc, 0x54, 0xfd, 0xca, 0xc4, 0xa2, 0x82, 0x64, 0x08, 0x09, 0x56, 0x0e, 0x61, 0x42, 0xb4, 0x2a, 0x49, 0x72, 0xb1, 0x07, 0xa5, 0x16, 0x96, 0xa6, 0x16, 0x97, 0x08, 0xf1, 0x71, 0x31, 0x65, 0xe6, 0x49, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x06, 0x31, 0x65, 0xe6, 0x29, 0xc9, 0x70, 0x71, 0x04, 0xa5, 0x16, 0x17, 0xe4, 0xe7, 0x15, 0xa7, 0x0a, 0x09, 0x70, 0x31, 0xe7, 0x97, 0x96, 0x40, 0x25, 0x41, 0x4c, 0xa3, 0x0a, 0x2e, 0x66, 0xb7, 0xfc, 0x7c, 0x21, 0x03, 0x2e, 0xee, 0xd0, 0xbc, 0xc4, 0xa2, 0x4a, 0xdf, 0xd4, 0x92, 0x8c, 0xfc, 0x14, 0x21, 0x1e, 0x3d, 0x90, 0xab, 0xa0, 0x26, 0x4a, 0xf1, 0x42, 0x79, 0x10, 0x43, 0x94, 0x58, 0x1a, 0xb6, 0x4a, 0x30, 0x08, 0x59, 0x72, 0x09, 0x05, 0xa7, 0x16, 0x95, 0xa5, 0x16, 0x05, 0x97, 0x14, 0xa5, 0x26, 0xe6, 0x12, 0xab, 0x91, 0xd1, 0x80, 0x51, 0x0a, 0x6c, 0x40, 0x12, 0x1b, 0xd8, 0xe5, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x29, 0xba, 0xb4, 0xf3, 0x0a, 0x01, 0x00, 0x00, } yarpc-0.0.1/test/foo/foo.proto000066400000000000000000000007141331225777200162530ustar00rootroot00000000000000syntax = "proto3"; package foo; import "github.com/influxdata/yarpc/yarpcproto/yarpc.proto"; service Foo { option (yarpcproto.yarpc_service_index) = 0x00; rpc UnaryMethod(Request) returns (Response){ option (yarpcproto.yarpc_method_index) = 0x00; } rpc ServerStreamMethod(Request) returns (stream Response){ option (yarpcproto.yarpc_method_index) = 0x01; } } message Request { string in = 1; } message Response { string out = 1; } yarpc-0.0.1/test/foo/foo.yarpc.go000066400000000000000000000071301331225777200166310ustar00rootroot00000000000000// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: test/foo/foo.proto /* Package foo is a generated protocol buffer package. It is generated from these files: test/foo/foo.proto It has these top-level messages: Request Response */ package foo import ( context "context" yarpc "github.com/influxdata/yarpc" ) import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/influxdata/yarpc/yarpcproto" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ yarpc.ClientConn // This is a compile-time assertion to ensure that this generated file // is compatible with the yarpc package it is being compiled against. const _ = yarpc.SupportPackageIsVersion1 // Client API for Foo service type FooClient interface { UnaryMethod(ctx context.Context, in *Request) (*Response, error) ServerStreamMethod(ctx context.Context, in *Request) (Foo_ServerStreamMethodClient, error) } type fooClient struct { cc *yarpc.ClientConn } func NewFooClient(cc *yarpc.ClientConn) FooClient { return &fooClient{cc} } func (c *fooClient) UnaryMethod(ctx context.Context, in *Request) (*Response, error) { out := new(Response) err := yarpc.Invoke(ctx, 0x0000, in, out, c.cc) if err != nil { return nil, err } return out, nil } func (c *fooClient) ServerStreamMethod(ctx context.Context, in *Request) (Foo_ServerStreamMethodClient, error) { stream, err := yarpc.NewClientStream(ctx, &_Foo_serviceDesc.Streams[0], c.cc, 0x0001) if err != nil { return nil, err } x := &fooServerStreamMethodClient{stream} if err := x.ClientStream.SendMsg(in); err != nil { return nil, err } return x, nil } type Foo_ServerStreamMethodClient interface { Recv() (*Response, error) yarpc.ClientStream } type fooServerStreamMethodClient struct { yarpc.ClientStream } func (x *fooServerStreamMethodClient) Recv() (*Response, error) { m := new(Response) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // Server API for Foo service type FooServer interface { UnaryMethod(context.Context, *Request) (*Response, error) ServerStreamMethod(*Request, Foo_ServerStreamMethodServer) error } func RegisterFooServer(s *yarpc.Server, srv FooServer) { s.RegisterService(&_Foo_serviceDesc, srv) } func _Foo_UnaryMethod_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error) (interface{}, error) { in := new(Request) if err := dec(in); err != nil { return nil, err } return srv.(FooServer).UnaryMethod(ctx, in) } func _Foo_ServerStreamMethod_Handler(srv interface{}, stream yarpc.ServerStream) error { m := new(Request) if err := stream.RecvMsg(m); err != nil { return err } return srv.(FooServer).ServerStreamMethod(m, &fooServerStreamMethodServer{stream}) } type Foo_ServerStreamMethodServer interface { Send(*Response) error yarpc.ServerStream } type fooServerStreamMethodServer struct { yarpc.ServerStream } func (x *fooServerStreamMethodServer) Send(m *Response) error { return x.ServerStream.SendMsg(m) } var _Foo_serviceDesc = yarpc.ServiceDesc{ ServiceName: "foo.Foo", Index: 0, HandlerType: (*FooServer)(nil), Methods: []yarpc.MethodDesc{ { MethodName: "UnaryMethod", Index: 0, Handler: _Foo_UnaryMethod_Handler, }, }, Streams: []yarpc.StreamDesc{ { StreamName: "ServerStreamMethod", Index: 1, Handler: _Foo_ServerStreamMethod_Handler, ServerStreams: true, }, }, Metadata: "test/foo/foo.proto", } yarpc-0.0.1/test/foo/foo_test.go000066400000000000000000000034221331225777200165530ustar00rootroot00000000000000package foo import ( "context" "fmt" "net" "testing" "github.com/influxdata/yarpc" ) type fooTestServer struct { } func (f *fooTestServer) UnaryMethod(ctx context.Context, in *Request) (*Response, error) { return &Response{"world"}, nil } func (f *fooTestServer) ServerStreamMethod(in *Request, stm Foo_ServerStreamMethodServer) error { for i := 0; i < 10; i++ { err := stm.Send(&Response{fmt.Sprintf("val %d", i)}) if err != nil { println("server stream error", err.Error()) return err } } return nil } func makeServer(t testing.TB) (l net.Listener, s *yarpc.Server, addr string) { var err error l, err = net.Listen("tcp", ":4040") if err != nil { t.Fatal("couldn't start listener", err) } s = yarpc.NewServer(yarpc.CustomCodec(&fooCodec{})) RegisterFooServer(s, &fooTestServer{}) addr = l.Addr().String() return } func TestFooClient_UnaryMethod(t *testing.T) { l, s, _ := makeServer(t) go func() { s.Serve(l) }() defer s.Stop() cc, err := yarpc.Dial(":4040", yarpc.WithCodec(&fooCodec{})) if err != nil { t.Fatal("couldn't dial server", err) } fs := NewFooClient(cc) in := &Request{"hello"} val, err := fs.UnaryMethod(context.Background(), in) if err != nil { t.Errorf("unexpected error: %v", err) } t.Log(*val) } func TestFooClient_ServerStreamMethod(t *testing.T) { l, s, _ := makeServer(t) go func() { s.Serve(l) }() defer s.Stop() cc, err := yarpc.Dial(":4040", yarpc.WithCodec(&fooCodec{})) if err != nil { t.Fatal("couldn't dial server", err) } fs := NewFooClient(cc) in := &Request{"hello"} stream, err := fs.ServerStreamMethod(context.Background(), in) if err != nil { t.Errorf("unexpected error: %v", err) } for { val, err := stream.Recv() if err != nil { t.Log("EOF") break } t.Log(val.Out) } } yarpc-0.0.1/yarpcproto/000077500000000000000000000000001331225777200150415ustar00rootroot00000000000000yarpc-0.0.1/yarpcproto/helper.go000066400000000000000000000014371331225777200166540ustar00rootroot00000000000000package yarpcproto import ( "reflect" proto "github.com/gogo/protobuf/proto" google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" ) func GetServiceIndex(service *google_protobuf.ServiceDescriptorProto) int { return GetIntExtension(service.Options, E_YarpcServiceIndex, -1) } func GetMethodIndex(service *google_protobuf.MethodDescriptorProto) int { return GetIntExtension(service.Options, E_YarpcMethodIndex, -1) } func GetIntExtension(pb proto.Message, extension *proto.ExtensionDesc, ifnotset int) int { if reflect.ValueOf(pb).IsNil() { return ifnotset } value, err := proto.GetExtension(pb, extension) if err != nil { return ifnotset } if value == nil { return ifnotset } if value.(*uint32) == nil { return ifnotset } return int(*(value.(*uint32))) } yarpc-0.0.1/yarpcproto/yarpc.pb.go000066400000000000000000000055231331225777200171130ustar00rootroot00000000000000// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: yarpcproto/yarpc.proto /* Package yarpcproto is a generated protocol buffer package. It is generated from these files: yarpcproto/yarpc.proto It has these top-level messages: */ package yarpcproto import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package var E_YarpcServiceIndex = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.ServiceOptions)(nil), ExtensionType: (*uint32)(nil), Field: 50000, Name: "yarpcproto.yarpc_service_index", Tag: "varint,50000,opt,name=yarpc_service_index,json=yarpcServiceIndex", Filename: "yarpcproto/yarpc.proto", } var E_YarpcMethodIndex = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MethodOptions)(nil), ExtensionType: (*uint32)(nil), Field: 50000, Name: "yarpcproto.yarpc_method_index", Tag: "varint,50000,opt,name=yarpc_method_index,json=yarpcMethodIndex", Filename: "yarpcproto/yarpc.proto", } func init() { proto.RegisterExtension(E_YarpcServiceIndex) proto.RegisterExtension(E_YarpcMethodIndex) } func init() { proto.RegisterFile("yarpcproto/yarpc.proto", fileDescriptorYarpc) } var fileDescriptorYarpc = []byte{ // 177 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0xab, 0x4c, 0x2c, 0x2a, 0x48, 0x2e, 0x28, 0xca, 0x2f, 0xc9, 0xd7, 0x07, 0x33, 0xf5, 0xc0, 0x6c, 0x21, 0x2e, 0x84, 0xb8, 0x94, 0x42, 0x7a, 0x7e, 0x7e, 0x7a, 0x4e, 0xaa, 0x3e, 0x98, 0x97, 0x54, 0x9a, 0xa6, 0x9f, 0x92, 0x5a, 0x9c, 0x5c, 0x94, 0x59, 0x50, 0x92, 0x5f, 0x04, 0x51, 0x6d, 0x15, 0xc8, 0x25, 0x0c, 0x56, 0x1f, 0x5f, 0x9c, 0x5a, 0x54, 0x96, 0x99, 0x9c, 0x1a, 0x9f, 0x99, 0x97, 0x92, 0x5a, 0x21, 0x24, 0xaf, 0x07, 0xd1, 0xa9, 0x07, 0xd3, 0xa9, 0x17, 0x0c, 0x91, 0xf7, 0x2f, 0x28, 0xc9, 0xcc, 0xcf, 0x2b, 0x96, 0xb8, 0xd0, 0xc6, 0xac, 0xc0, 0xa8, 0xc1, 0x1b, 0x24, 0x08, 0xd6, 0x0d, 0x95, 0xf4, 0x04, 0xe9, 0xb5, 0xf2, 0xe3, 0x12, 0x82, 0x18, 0x99, 0x9b, 0x5a, 0x92, 0x91, 0x9f, 0x02, 0x35, 0x51, 0x0e, 0xc3, 0x44, 0x5f, 0xb0, 0x34, 0xba, 0x81, 0x02, 0x60, 0xbd, 0x10, 0x39, 0xb0, 0x79, 0x4e, 0x02, 0x27, 0x1e, 0xc9, 0x31, 0x5e, 0x78, 0x24, 0xc7, 0xf8, 0xe0, 0x91, 0x1c, 0xe3, 0x84, 0xc7, 0x72, 0x0c, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xfd, 0x27, 0x26, 0x95, 0xfb, 0x00, 0x00, 0x00, } yarpc-0.0.1/yarpcproto/yarpc.proto000066400000000000000000000004041331225777200172420ustar00rootroot00000000000000syntax = "proto2"; package yarpcproto; import "google/protobuf/descriptor.proto"; extend google.protobuf.ServiceOptions { optional uint32 yarpc_service_index = 50000; } extend google.protobuf.MethodOptions { optional uint32 yarpc_method_index = 50000; }