|
| 1 | +// protoc-gen-connect-go-servicestruct is a plugin for the Protobuf compiler that generates |
| 2 | +// Go service structs with handler functions. To use it, build this program and make |
| 3 | +// it available on your PATH as protoc-gen-connect-go-servicestruct. |
| 4 | +// |
| 5 | +// The 'connect-go-servicestruct' suffix becomes part of the arguments for the Protobuf |
| 6 | +// compiler. To generate service structs using protoc: |
| 7 | +// |
| 8 | +// protoc --go_out=gen --connect-go-servicestruct_out=gen path/to/file.proto |
| 9 | +// |
| 10 | +// With [buf], your buf.gen.yaml will look like this: |
| 11 | +// |
| 12 | +// version: v2 |
| 13 | +// plugins: |
| 14 | +// - local: protoc-gen-go |
| 15 | +// out: gen |
| 16 | +// - local: protoc-gen-connect-go-servicestruct |
| 17 | +// out: gen |
| 18 | +// |
| 19 | +// This generates service struct definitions for the Protobuf services |
| 20 | +// defined by file.proto. If file.proto defines the foov1 Protobuf package, the |
| 21 | +// invocations above will write output to: |
| 22 | +// |
| 23 | +// gen/path/to/file.pb.go |
| 24 | +// gen/path/to/foov1connect/file.servicestruct.connect.go |
| 25 | +// |
| 26 | +// [buf]: https://buf.build |
| 27 | +package main |
| 28 | + |
| 29 | +import ( |
| 30 | + "fmt" |
| 31 | + "os" |
| 32 | + "path" |
| 33 | + "strings" |
| 34 | + |
| 35 | + connect "connectrpc.com/connect" |
| 36 | + "google.golang.org/protobuf/compiler/protogen" |
| 37 | + "google.golang.org/protobuf/types/descriptorpb" |
| 38 | + "google.golang.org/protobuf/types/pluginpb" |
| 39 | +) |
| 40 | + |
| 41 | +const ( |
| 42 | + contextPackage = protogen.GoImportPath("context") |
| 43 | + connectPackage = protogen.GoImportPath("connectrpc.com/connect") |
| 44 | + |
| 45 | + filenameSuffix = ".servicestruct.connect.go" |
| 46 | + handlerFuncSuffix = "HandlerFunc" |
| 47 | + serviceSuffix = "Struct" |
| 48 | + |
| 49 | + usage = "\n\nFlags:\n -h, --help\tPrint this help and exit.\n --version\tPrint the version and exit." |
| 50 | +) |
| 51 | + |
| 52 | +func main() { |
| 53 | + if len(os.Args) == 2 && os.Args[1] == "--version" { |
| 54 | + if _, err := fmt.Fprintln(os.Stdout, connect.Version); err != nil { |
| 55 | + os.Exit(1) |
| 56 | + } |
| 57 | + os.Exit(0) |
| 58 | + } |
| 59 | + if len(os.Args) == 2 && (os.Args[1] == "-h" || os.Args[1] == "--help") { |
| 60 | + if _, err := fmt.Fprintln(os.Stdout, usage); err != nil { |
| 61 | + os.Exit(1) |
| 62 | + } |
| 63 | + os.Exit(0) |
| 64 | + } |
| 65 | + if len(os.Args) != 1 { |
| 66 | + if _, err := fmt.Fprintln(os.Stderr, usage); err != nil { |
| 67 | + os.Exit(1) |
| 68 | + } |
| 69 | + os.Exit(1) |
| 70 | + } |
| 71 | + protogen.Options{}.Run( |
| 72 | + func(plugin *protogen.Plugin) error { |
| 73 | + plugin.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL) | uint64(pluginpb.CodeGeneratorResponse_FEATURE_SUPPORTS_EDITIONS) |
| 74 | + plugin.SupportedEditionsMinimum = descriptorpb.Edition_EDITION_PROTO2 |
| 75 | + plugin.SupportedEditionsMaximum = descriptorpb.Edition_EDITION_2023 |
| 76 | + |
| 77 | + for _, file := range plugin.Files { |
| 78 | + if file.Generate && len(file.Services) > 0 { |
| 79 | + generateFile(plugin, file) |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + return nil |
| 84 | + }, |
| 85 | + ) |
| 86 | +} |
| 87 | + |
| 88 | +func generateFile(plugin *protogen.Plugin, file *protogen.File) { |
| 89 | + // Modify package name and paths to match connect plugin behavior |
| 90 | + connectSuffix := "connect" |
| 91 | + connectPackageName := file.GoPackageName + protogen.GoPackageName(connectSuffix) |
| 92 | + dir := path.Dir(file.GeneratedFilenamePrefix) |
| 93 | + base := path.Base(file.GeneratedFilenamePrefix) |
| 94 | + connectDir := string(file.GoPackageName) + connectSuffix |
| 95 | + filename := path.Join(dir, connectDir, base+filenameSuffix) |
| 96 | + goImportPath := protogen.GoImportPath(path.Join( |
| 97 | + string(file.GoImportPath), |
| 98 | + connectDir, |
| 99 | + )) |
| 100 | + generatedFile := plugin.NewGeneratedFile(filename, goImportPath) |
| 101 | + |
| 102 | + // Import the base package for message types |
| 103 | + generatedFile.Import(file.GoImportPath) |
| 104 | + |
| 105 | + generatedFile.P("// Code generated by protoc-gen-connect-go-servicestruct. DO NOT EDIT.") |
| 106 | + generatedFile.P("//") |
| 107 | + generatedFile.P("// Source: ", file.Desc.Path()) |
| 108 | + generatedFile.P() |
| 109 | + generatedFile.P("package ", connectPackageName) |
| 110 | + generatedFile.P() |
| 111 | + |
| 112 | + generateHandlerFuncTypes(generatedFile, []*protogen.File{file}) |
| 113 | + |
| 114 | + for _, service := range file.Services { |
| 115 | + generateServiceStruct(generatedFile, service) |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +func generateHandlerFuncTypes(g *protogen.GeneratedFile, files []*protogen.File) { |
| 120 | + // Generate specific handler function types for each method |
| 121 | + for _, file := range files { |
| 122 | + for _, service := range file.Services { |
| 123 | + for _, method := range service.Methods { |
| 124 | + generateMethodHandlerType(g, service, method) |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | +} |
| 129 | + |
| 130 | +func generateMethodHandlerType(g *protogen.GeneratedFile, service *protogen.Service, method *protogen.Method) { |
| 131 | + typeName := service.GoName + method.GoName + handlerFuncSuffix |
| 132 | + |
| 133 | + if isDeprecatedMethod(method) { |
| 134 | + g.P("//") |
| 135 | + deprecated(g) |
| 136 | + } |
| 137 | + |
| 138 | + // Generate the appropriate function signature based on streaming type |
| 139 | + isStreamingClient := method.Desc.IsStreamingClient() |
| 140 | + isStreamingServer := method.Desc.IsStreamingServer() |
| 141 | + |
| 142 | + switch { |
| 143 | + case isStreamingClient && isStreamingServer: |
| 144 | + // Bidirectional streaming |
| 145 | + g.P("type ", typeName, " func(", contextPackage.Ident("Context"), ", *", connectPackage.Ident("BidiStream"), "[", g.QualifiedGoIdent(method.Input.GoIdent), ", ", g.QualifiedGoIdent(method.Output.GoIdent), "]) error") |
| 146 | + case isStreamingClient && !isStreamingServer: |
| 147 | + // Client streaming |
| 148 | + g.P("type ", typeName, " func(", contextPackage.Ident("Context"), ", *", connectPackage.Ident("ClientStream"), "[", g.QualifiedGoIdent(method.Input.GoIdent), "]) (*", connectPackage.Ident("Response"), "[", g.QualifiedGoIdent(method.Output.GoIdent), "], error)") |
| 149 | + case !isStreamingClient && isStreamingServer: |
| 150 | + // Server streaming |
| 151 | + g.P("type ", typeName, " func(", contextPackage.Ident("Context"), ", *", connectPackage.Ident("Request"), "[", g.QualifiedGoIdent(method.Input.GoIdent), "], *", connectPackage.Ident("ServerStream"), "[", g.QualifiedGoIdent(method.Output.GoIdent), "]) error") |
| 152 | + default: |
| 153 | + // Unary |
| 154 | + g.P("type ", typeName, " func(", contextPackage.Ident("Context"), ", *", connectPackage.Ident("Request"), "[", g.QualifiedGoIdent(method.Input.GoIdent), "]) (*", connectPackage.Ident("Response"), "[", g.QualifiedGoIdent(method.Output.GoIdent), "], error)") |
| 155 | + } |
| 156 | + g.P() |
| 157 | +} |
| 158 | + |
| 159 | +func generateServiceStruct(g *protogen.GeneratedFile, service *protogen.Service) { |
| 160 | + serviceName := fmt.Sprintf("%s%s", service.GoName, serviceSuffix) |
| 161 | + |
| 162 | + if isDeprecatedService(service) { |
| 163 | + g.P("//") |
| 164 | + deprecated(g) |
| 165 | + } |
| 166 | + g.AnnotateSymbol(serviceName, protogen.Annotation{Location: service.Location}) |
| 167 | + g.P("type ", serviceName, " struct {") |
| 168 | + for _, method := range service.Methods { |
| 169 | + fieldName := method.GoName + "Func" |
| 170 | + g.AnnotateSymbol(serviceName+"."+fieldName, protogen.Annotation{Location: method.Location}) |
| 171 | + leadingComments( |
| 172 | + g, |
| 173 | + method.Comments.Leading, |
| 174 | + isDeprecatedMethod(method), |
| 175 | + ) |
| 176 | + handlerTypeName := service.GoName + method.GoName + handlerFuncSuffix |
| 177 | + g.P(fieldName, " ", handlerTypeName) |
| 178 | + } |
| 179 | + g.P("}") |
| 180 | + g.P() |
| 181 | + |
| 182 | + for _, method := range service.Methods { |
| 183 | + fieldName := method.GoName + "Func" |
| 184 | + if isDeprecatedMethod(method) { |
| 185 | + g.P("//") |
| 186 | + deprecated(g) |
| 187 | + } |
| 188 | + methodSig := method.GoName + serverSignatureParams(g, method, true) |
| 189 | + g.P("func (s *", serviceName, ") ", methodSig, " {") |
| 190 | + |
| 191 | + isStreamingClient := method.Desc.IsStreamingClient() |
| 192 | + isStreamingServer := method.Desc.IsStreamingServer() |
| 193 | + |
| 194 | + switch { |
| 195 | + case isStreamingClient && isStreamingServer: |
| 196 | + g.P("return s.", fieldName, "(ctx, stream)") |
| 197 | + case isStreamingClient && !isStreamingServer: |
| 198 | + g.P("return s.", fieldName, "(ctx, stream)") |
| 199 | + case !isStreamingClient && isStreamingServer: |
| 200 | + g.P("return s.", fieldName, "(ctx, req, stream)") |
| 201 | + default: |
| 202 | + g.P("return s.", fieldName, "(ctx, req)") |
| 203 | + } |
| 204 | + g.P("}") |
| 205 | + g.P() |
| 206 | + } |
| 207 | +} |
| 208 | + |
| 209 | +func serverSignatureParams(g *protogen.GeneratedFile, method *protogen.Method, named bool) string { |
| 210 | + ctxName := "ctx " |
| 211 | + reqName := "req " |
| 212 | + streamName := "stream " |
| 213 | + if !named { |
| 214 | + ctxName, reqName, streamName = "", "", "" |
| 215 | + } |
| 216 | + if method.Desc.IsStreamingClient() && method.Desc.IsStreamingServer() { |
| 217 | + return "(" + ctxName + g.QualifiedGoIdent(contextPackage.Ident("Context")) + ", " + |
| 218 | + streamName + "*" + g.QualifiedGoIdent(connectPackage.Ident("BidiStream")) + |
| 219 | + "[" + g.QualifiedGoIdent(method.Input.GoIdent) + ", " + g.QualifiedGoIdent(method.Output.GoIdent) + "]" + |
| 220 | + ") error" |
| 221 | + } |
| 222 | + if method.Desc.IsStreamingClient() { |
| 223 | + return "(" + ctxName + g.QualifiedGoIdent(contextPackage.Ident("Context")) + ", " + |
| 224 | + streamName + "*" + g.QualifiedGoIdent(connectPackage.Ident("ClientStream")) + |
| 225 | + "[" + g.QualifiedGoIdent(method.Input.GoIdent) + "]" + |
| 226 | + ") (*" + g.QualifiedGoIdent(connectPackage.Ident("Response")) + "[" + g.QualifiedGoIdent(method.Output.GoIdent) + "], error)" |
| 227 | + } |
| 228 | + if method.Desc.IsStreamingServer() { |
| 229 | + return "(" + ctxName + g.QualifiedGoIdent(contextPackage.Ident("Context")) + |
| 230 | + ", " + reqName + "*" + g.QualifiedGoIdent(connectPackage.Ident("Request")) + "[" + |
| 231 | + g.QualifiedGoIdent(method.Input.GoIdent) + "], " + |
| 232 | + streamName + "*" + g.QualifiedGoIdent(connectPackage.Ident("ServerStream")) + |
| 233 | + "[" + g.QualifiedGoIdent(method.Output.GoIdent) + "]" + |
| 234 | + ") error" |
| 235 | + } |
| 236 | + return "(" + ctxName + g.QualifiedGoIdent(contextPackage.Ident("Context")) + |
| 237 | + ", " + reqName + "*" + g.QualifiedGoIdent(connectPackage.Ident("Request")) + "[" + |
| 238 | + g.QualifiedGoIdent(method.Input.GoIdent) + "]) " + |
| 239 | + "(*" + g.QualifiedGoIdent(connectPackage.Ident("Response")) + "[" + |
| 240 | + g.QualifiedGoIdent(method.Output.GoIdent) + "], error)" |
| 241 | +} |
| 242 | + |
| 243 | +func isDeprecatedService(service *protogen.Service) bool { |
| 244 | + serviceOptions, ok := service.Desc.Options().(*descriptorpb.ServiceOptions) |
| 245 | + return ok && serviceOptions.GetDeprecated() |
| 246 | +} |
| 247 | + |
| 248 | +func isDeprecatedMethod(method *protogen.Method) bool { |
| 249 | + methodOptions, ok := method.Desc.Options().(*descriptorpb.MethodOptions) |
| 250 | + return ok && methodOptions.GetDeprecated() |
| 251 | +} |
| 252 | + |
| 253 | +func leadingComments(g *protogen.GeneratedFile, comments protogen.Comments, isDeprecated bool) { |
| 254 | + if comments.String() != "" { |
| 255 | + g.P(strings.TrimSpace(comments.String())) |
| 256 | + } |
| 257 | + if isDeprecated { |
| 258 | + if comments.String() != "" { |
| 259 | + g.P("//") |
| 260 | + } |
| 261 | + deprecated(g) |
| 262 | + } |
| 263 | +} |
| 264 | + |
| 265 | +func deprecated(g *protogen.GeneratedFile) { |
| 266 | + g.P("// Deprecated: do not use.") |
| 267 | +} |
0 commit comments