-
Notifications
You must be signed in to change notification settings - Fork 11
/
orion.go
432 lines (389 loc) · 11.3 KB
/
orion.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// protoc-gen-orion is a plugin for the Google protocol buffer compiler to generate
// Orion Go code. Run it by building this program and putting it in your path with
// the name
// protoc-gen-orion
//
// The generated code is documented in the package comment for
// the library.
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"text/template"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"github.com/micro/protobuf/protoc-gen-go/generator"
)
// constants for Orion protoc generator
const (
ORION = "ORION"
URL = "URL"
DELIM = ":"
OPTION = "OPTION"
MIDDLEWARE = "MIDDLEWARE"
MIDDLEWARES = "MIDDLEWARES"
)
type commentsInfo struct {
Method string
Path string
Decoder bool
Encoder bool
Option bool
Middleware bool
Value string
}
type data struct {
FileName string
PackageName string
Services []*service
}
type service struct {
ServName string
ServiceDescVar string
Encoders []*encoder
Decoders []*decoder
Handlers []*handler
Options []*orionOption
Middlewares []*orionMiddleware
Streams []*stream
}
type encoder struct {
SvcName string
MethodName string
Path string
Methods string
}
type decoder struct {
SvcName string
MethodName string
}
type handler struct {
SvcName string
MethodName string
Path string
}
type stream struct {
SvcName string
MethodName string
Path string
ClientStream bool
ServerStream bool
Methods string
}
type orionOption struct {
SvcName string
MethodName string
OptionType string
}
type orionMiddleware struct {
SvcName string
MethodName string
Names string
}
var tmpl = `// Code generated by protoc-gen-orion. DO NOT EDIT.
// source: {{ .FileName }}
package {{ .PackageName }}
{{ if .Services }}
import (
orion "github.com/carousell/Orion/orion"
)
// If you see error please update your orion-protoc-gen by running 'go get -u github.com/carousell/Orion/protoc-gen-orion'
var _ = orion.ProtoGenVersion1_0
{{ end }}
{{ range .Services -}}
// Encoders
{{ range .Encoders }}
// Register{{.SvcName}}{{.MethodName}}Encoder registers the encoder for {{.MethodName}} method in {{.SvcName}}
// it registers HTTP {{ if .Path }} path {{.Path}} {{ end }}with {{.Methods}} methods
func Register{{.SvcName}}{{.MethodName}}Encoder(svr orion.Server, encoder orion.Encoder) {
orion.RegisterEncoders(svr, "{{.SvcName}}", "{{.MethodName}}", []string{ {{- .Methods -}} }, "{{.Path}}", encoder)
}
{{ end }}
// Handlers
{{ range .Handlers }}
// Register{{.SvcName}}{{.MethodName}}Handler registers the handler for {{.MethodName}} method in {{.SvcName}}
func Register{{.SvcName}}{{.MethodName}}Handler(svr orion.Server, handler orion.HTTPHandler) {
orion.RegisterHandler(svr, "{{.SvcName}}", "{{.MethodName}}", "{{.Path}}", handler)
}
{{ end }}
// Decoders
{{ range .Decoders }}
// Register{{.SvcName}}{{.MethodName}}Decoder registers the decoder for {{.MethodName}} method in {{.SvcName}}
func Register{{.SvcName}}{{.MethodName}}Decoder(svr orion.Server, decoder orion.Decoder) {
orion.RegisterDecoder(svr, "{{.SvcName}}", "{{.MethodName}}", decoder)
}
{{ end }}
//Streams
{{ range .Streams }}
// {{ . }}
{{ end }}
// Register{{.ServName}}OrionServer registers {{.ServName}} to Orion server
// Services need to pass either ServiceFactory or ServiceFactoryV2 implementation
func Register{{.ServName}}OrionServer(sf interface{}, orionServer orion.Server) error {
err := orionServer.RegisterService(&{{.ServiceDescVar}}, sf)
if err != nil {
return err
}
{{ range .Encoders }}
Register{{.SvcName}}{{.MethodName}}Encoder(orionServer, nil)
{{- end }}
{{- range .Options }}
orion.RegisterMethodOption(orionServer, "{{.SvcName}}", "{{.MethodName}}", "{{.OptionType}}")
{{- end }}
{{- range .Middlewares }}
orion.RegisterMiddleware(orionServer, "{{.SvcName}}", "{{.MethodName}}", {{.Names}})
{{- end }}
return nil
}
// DefaultEncoder
func Register{{.ServName}}DefaultEncoder(svr orion.Server, encoder orion.Encoder) {
orion.RegisterDefaultEncoder(svr, "{{.ServName}}", encoder)
}
// DefaultDecoder
func Register{{.ServName}}DefaultDecoder(svr orion.Server, decoder orion.Decoder) {
orion.RegisterDefaultDecoder(svr, "{{.ServName}}", decoder)
}
{{ end }}
`
// Error reports a problem, including an error, and exits the program.
func logError(err error, msgs ...string) {
s := strings.Join(msgs, " ") + ":" + err.Error()
log.Print("protoc-gen-orion: error:", s)
os.Exit(1)
}
// Fail reports a problem and exits the program.
func logFail(msgs ...string) {
s := strings.Join(msgs, " ")
log.Print("protoc-gen-orion: error:", s)
os.Exit(1)
}
func main() {
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
logError(err, "reading input")
}
request := new(plugin.CodeGeneratorRequest)
if err := proto.Unmarshal(data, request); err != nil {
logError(err, "parsing input proto")
}
if len(request.FileToGenerate) == 0 {
logFail("no files to generate")
}
filesToGenerate := make(map[string]bool)
for _, v := range request.FileToGenerate {
filesToGenerate[v] = true
}
response := new(plugin.CodeGeneratorResponse)
response.File = make([]*plugin.CodeGeneratorResponse_File, 0)
for _, file := range request.GetProtoFile() {
if _, ok := filesToGenerate[file.GetName()]; ok {
// check if file has any service
if len(file.Service) > 0 {
f := generateFile(populate(file))
response.File = append(response.File, f)
}
}
}
// Send back the results.
data, err = proto.Marshal(response)
if err != nil {
logError(err, "failed to marshal output proto")
}
_, err = os.Stdout.Write(data)
if err != nil {
logError(err, "failed to write output proto")
}
}
func generateFile(d *data) *plugin.CodeGeneratorResponse_File {
t := template.New("file")
t, err := t.Parse(tmpl)
if err != nil {
logError(err, "failed parsing template")
}
buf := new(bytes.Buffer)
err = t.Execute(buf, d)
if err != nil {
logError(err, "failed parsing template")
}
file := new(plugin.CodeGeneratorResponse_File)
file.Content = proto.String(buf.String())
file.Name = proto.String(d.FileName + ".orion.pb.go")
return file
}
func populate(file *descriptor.FileDescriptorProto) *data {
d := new(data)
d.FileName = *file.Name
d.PackageName = strings.Replace(file.GetPackage(), ".", "_", 10)
d.Services = make([]*service, 0)
generate(d, file)
return d
}
func generate(d *data, file *descriptor.FileDescriptorProto) {
comments := extractComments(file)
for index, svc := range file.GetService() {
origServName := svc.GetName()
servName := generator.CamelCase(origServName) // use the same logic from go-grpc generator
serviceDescVar := "_" + servName + "_serviceDesc"
s := new(service)
s.Encoders = make([]*encoder, 0)
s.Handlers = make([]*handler, 0)
s.Decoders = make([]*decoder, 0)
s.Options = make([]*orionOption, 0)
s.Middlewares = make([]*orionMiddleware, 0)
s.Streams = make([]*stream, 0)
s.ServiceDescVar = serviceDescVar
s.ServName = servName
d.Services = append(d.Services, s)
// ** --- START -- Find comments in grpc services
path := fmt.Sprintf("6,%d", index) // 6 means service.
for i, method := range svc.GetMethod() {
commentPath := fmt.Sprintf("%s,2,%d", path, i) // 2 means method in a service.
if loc, ok := comments[commentPath]; ok {
text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
for _, line := range strings.Split(text, "\n") {
// ** --- END -- Find comments in grpc services
if option := parseComments(line); option != nil {
if method.GetClientStreaming() || method.GetServerStreaming() {
str := new(stream)
str.SvcName = svc.GetName()
str.MethodName = method.GetName()
str.ClientStream = method.GetClientStreaming()
str.ServerStream = method.GetServerStreaming()
if option.Encoder || option.Decoder {
str.Path = option.Path
str.Methods = option.Method
}
s.Streams = append(s.Streams, str)
} else { // dont add others for streaming use cases
if option.Encoder {
methods := strings.Split(option.Method, "/")
for i := range methods {
if strings.ToLower(methods[i]) == "options" {
}
methods[i] = "\"" + methods[i] + "\""
}
methodsString := strings.Join(methods, ", ")
// populate encoder
enc := new(encoder)
enc.SvcName = svc.GetName()
enc.MethodName = method.GetName()
enc.Path = option.Path
enc.Methods = methodsString
s.Encoders = append(s.Encoders, enc)
// popluate handler
han := new(handler)
han.SvcName = svc.GetName()
han.MethodName = method.GetName()
han.Path = option.Path
s.Handlers = append(s.Handlers, han)
}
if option.Decoder {
// popluate decoder
dec := new(decoder)
dec.SvcName = svc.GetName()
dec.MethodName = method.GetName()
s.Decoders = append(s.Decoders, dec)
}
if option.Option {
opt := new(orionOption)
opt.SvcName = svc.GetName()
opt.MethodName = method.GetName()
opt.OptionType = strings.TrimSpace(option.Value)
s.Options = append(s.Options, opt)
}
if option.Middleware {
mid := new(orionMiddleware)
mid.SvcName = svc.GetName()
mid.MethodName = method.GetName()
names := strings.Split(option.Value, ",")
for i := range names {
names[i] = "\"" + strings.TrimSpace(names[i]) + "\""
}
mid.Names = strings.Join(names, ", ")
s.Middlewares = append(s.Middlewares, mid)
}
}
}
}
}
}
}
}
func parseCommentURL(parts []string) *commentsInfo {
if len(parts) > 2 {
values := strings.SplitN(strings.TrimSpace(parts[2]), " ", 2)
if len(values) == 2 {
return &commentsInfo{
Method: strings.ToUpper(values[0]),
Path: values[1],
Encoder: true,
Decoder: true,
}
}
return &commentsInfo{
Method: strings.ToUpper(values[0]),
Path: "",
Encoder: true,
Decoder: true,
}
}
return &commentsInfo{
Decoder: true,
}
}
func parseMiddlewares(parts []string) *commentsInfo {
if len(parts) > 2 {
return &commentsInfo{
Middleware: true,
Value: parts[2],
}
}
return nil
}
func parseCommentOptions(parts []string) *commentsInfo {
if len(parts) > 2 {
return &commentsInfo{
Option: true,
Value: strings.ToUpper(parts[2]),
}
}
return nil
}
func parseComments(line string) *commentsInfo {
parts := strings.SplitN(line, DELIM, 3)
if len(parts) > 1 {
if ORION == strings.ToUpper(strings.TrimSpace(parts[0])) {
switch strings.ToUpper(strings.TrimSpace(parts[1])) {
case URL:
return parseCommentURL(parts)
case OPTION:
return parseCommentOptions(parts)
case MIDDLEWARES:
fallthrough
case MIDDLEWARE:
return parseMiddlewares(parts)
}
}
}
return nil
}
func extractComments(file *descriptor.FileDescriptorProto) map[string]*descriptor.SourceCodeInfo_Location {
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)))
}
comments[strings.Join(p, ",")] = loc
}
return comments
}