-
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathservice.go
331 lines (305 loc) Β· 9.75 KB
/
service.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
package service
import (
"fmt"
"path/filepath"
"goa.design/goa/codegen"
"goa.design/goa/expr"
)
// File returns the service file for the given service.
func File(genpkg string, service *expr.ServiceExpr) *codegen.File {
svc := Services.Get(service.Name)
svcName := codegen.SnakeCase(svc.VarName)
path := filepath.Join(codegen.Gendir, svcName, "service.go")
header := codegen.Header(
service.Name+" service",
svc.PkgName,
[]*codegen.ImportSpec{
{Path: "context"},
{Path: "goa.design/goa"},
{Path: "goa.design/goa/security"},
{Path: genpkg + "/" + svcName + "/" + "views", Name: svc.ViewsPkg},
})
def := &codegen.SectionTemplate{
Name: "service",
Source: serviceT,
Data: svc,
FuncMap: map[string]interface{}{
"streamInterfaceFor": streamInterfaceFor,
},
}
sections := []*codegen.SectionTemplate{header, def}
seen := make(map[string]struct{})
for _, m := range svc.Methods {
if m.PayloadDef != "" {
if _, ok := seen[m.Payload]; !ok {
seen[m.Payload] = struct{}{}
sections = append(sections, &codegen.SectionTemplate{
Name: "service-payload",
Source: payloadT,
Data: m,
})
}
}
if m.StreamingPayloadDef != "" {
if _, ok := seen[m.StreamingPayload]; !ok {
seen[m.StreamingPayload] = struct{}{}
sections = append(sections, &codegen.SectionTemplate{
Name: "service-streamig-payload",
Source: streamingPayloadT,
Data: m,
})
}
}
if m.ResultDef != "" {
if _, ok := seen[m.Result]; !ok {
seen[m.Result] = struct{}{}
sections = append(sections, &codegen.SectionTemplate{
Name: "service-result",
Source: resultT,
Data: m,
})
}
}
}
for _, ut := range svc.userTypes {
if _, ok := seen[ut.Name]; !ok {
sections = append(sections, &codegen.SectionTemplate{
Name: "service-user-type",
Source: userTypeT,
Data: ut,
})
}
}
var errorTypes []*UserTypeData
for _, et := range svc.errorTypes {
if et.Type == expr.ErrorResult {
continue
}
if _, ok := seen[et.Name]; !ok {
sections = append(sections, &codegen.SectionTemplate{
Name: "error-user-type",
Source: userTypeT,
Data: et,
})
errorTypes = append(errorTypes, et)
}
}
for _, et := range errorTypes {
sections = append(sections, &codegen.SectionTemplate{
Name: "service-error",
Source: errorT,
FuncMap: map[string]interface{}{"errorName": errorName},
Data: et,
})
}
for _, er := range svc.errorInits {
sections = append(sections, &codegen.SectionTemplate{
Name: "error-init-func",
Source: errorInitT,
Data: er,
})
}
// transform result type functions
for _, t := range svc.viewedResultTypes {
sections = append(sections, &codegen.SectionTemplate{
Name: "viewed-result-type-to-service-result-type",
Source: typeInitT,
Data: t.ResultInit,
})
sections = append(sections, &codegen.SectionTemplate{
Name: "service-result-type-to-viewed-result-type",
Source: typeInitT,
Data: t.Init,
})
}
var projh []*codegen.TransformFunctionData
for _, t := range svc.projectedTypes {
for _, i := range t.TypeInits {
projh = codegen.AppendHelpers(projh, i.Helpers)
sections = append(sections, &codegen.SectionTemplate{
Name: "projected-type-to-service-type",
Source: typeInitT,
Data: i,
})
}
for _, i := range t.Projections {
projh = codegen.AppendHelpers(projh, i.Helpers)
sections = append(sections, &codegen.SectionTemplate{
Name: "service-type-to-projected-type",
Source: typeInitT,
Data: i,
})
}
}
for _, h := range projh {
sections = append(sections, &codegen.SectionTemplate{
Name: "transform-helpers",
Source: transformHelperT,
Data: h,
})
}
return &codegen.File{Path: path, SectionTemplates: sections}
}
// AddServiceDataMetaTypeImports Adds all imports defined by struct:field:type from the service expr and the service data
func AddServiceDataMetaTypeImports(header *codegen.SectionTemplate, serviceE *expr.ServiceExpr) {
codegen.AddServiceMetaTypeImports(header, serviceE)
svc := Services.Get(serviceE.Name)
for _, ut := range svc.userTypes {
codegen.AddImport(header, codegen.GetMetaTypeImports(ut.Type.Attribute())...)
}
for _, et := range svc.errorTypes {
codegen.AddImport(header, codegen.GetMetaTypeImports(et.Type.Attribute())...)
}
for _, t := range svc.viewedResultTypes {
codegen.AddImport(header, codegen.GetMetaTypeImports(t.Type.Attribute())...)
}
for _, t := range svc.projectedTypes {
codegen.AddImport(header, codegen.GetMetaTypeImports(t.Type.Attribute())...)
}
}
func errorName(et *UserTypeData) string {
obj := expr.AsObject(et.Type)
if obj != nil {
for _, att := range *obj {
if _, ok := att.Attribute.Meta["struct:error:name"]; ok {
return fmt.Sprintf("e.%s", codegen.Goify(att.Name, true))
}
}
}
// if error type is a custom user type and used by at most one error, then
// error Finalize should have added "struct:error:name" to the user type
// attribute's meta.
if v, ok := et.Type.Attribute().Meta["struct:error:name"]; ok {
return fmt.Sprintf("%q", v[0])
}
return fmt.Sprintf("%q", et.Name)
}
// streamInterfaceFor builds the data to generate the client and server stream
// interfaces for the given endpoint.
func streamInterfaceFor(typ string, m *MethodData, stream *StreamData) map[string]interface{} {
return map[string]interface{}{
"Type": typ,
"Endpoint": m.Name,
"Stream": stream,
// If a view is explicitly set (ViewName is not empty) in the Result
// expression, we can use that view to render the result type instead
// of iterating through the list of views defined in the result type.
"IsViewedResult": m.ViewedResult != nil && m.ViewedResult.ViewName == "",
}
}
// serviceT is the template used to write an service definition.
const serviceT = `
{{ comment .Description }}
type Service interface {
{{- range .Methods }}
{{ comment .Description }}
{{- if .ViewedResult }}
{{- if not .ViewedResult.ViewName }}
{{ comment "The \"view\" return value must have one of the following views" }}
{{- range .ViewedResult.Views }}
{{- if .Description }}
{{ printf "// - %q: %s" .Name .Description }}
{{- else }}
{{ printf "// - %q" .Name }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}
{{- if .ServerStream }}
{{ .VarName }}(context.Context{{ if .Payload }}, {{ .PayloadRef }}{{ end }}, {{ .ServerStream.Interface }}) (err error)
{{- else }}
{{ .VarName }}(context.Context{{ if .Payload }}, {{ .PayloadRef }}{{ end }}) ({{ if .Result }}res {{ .ResultRef }}, {{ if .ViewedResult }}{{ if not .ViewedResult.ViewName }}view string, {{ end }}{{ end }}{{ end }}err error)
{{- end }}
{{- end }}
}
{{- if .Schemes }}
// Auther defines the authorization functions to be implemented by the service.
type Auther interface {
{{- range .Schemes }}
{{ printf "%sAuth implements the authorization logic for the %s security scheme." .Type .Type | comment }}
{{ .Type }}Auth(ctx context.Context, {{ if eq .Type "Basic" }}user, pass{{ else if eq .Type "APIKey" }}key{{ else }}token{{ end }} string, schema *security.{{ .Type }}Scheme) (context.Context, error)
{{- end }}
}
{{- end }}
// ServiceName is the name of the service as defined in the design. This is the
// same value that is set in the endpoint request contexts under the ServiceKey
// key.
const ServiceName = {{ printf "%q" .Name }}
// MethodNames lists the service method names as defined in the design. These
// are the same values that are set in the endpoint request contexts under the
// MethodKey key.
var MethodNames = [{{ len .Methods }}]string{ {{ range .Methods }}{{ printf "%q" .Name }}, {{ end }} }
{{- range .Methods }}
{{- if .ServerStream }}
{{ template "stream_interface" (streamInterfaceFor "server" . .ServerStream) }}
{{ template "stream_interface" (streamInterfaceFor "client" . .ClientStream) }}
{{- end }}
{{- end }}
{{- define "stream_interface" }}
{{ printf "%s is the interface a %q endpoint %s stream must satisfy." .Stream.Interface .Endpoint .Type | comment }}
type {{ .Stream.Interface }} interface {
{{- if .Stream.SendTypeRef }}
{{ comment .Stream.SendDesc }}
{{ .Stream.SendName }}({{ .Stream.SendTypeRef }}) error
{{- end }}
{{- if .Stream.RecvTypeRef }}
{{ comment .Stream.RecvDesc }}
{{ .Stream.RecvName }}() ({{ .Stream.RecvTypeRef }}, error)
{{- end }}
{{- if .Stream.MustClose }}
{{ comment "Close closes the stream." }}
Close() error
{{- end }}
{{- if and .IsViewedResult (eq .Type "server") }}
{{ comment "SetView sets the view used to render the result before streaming." }}
SetView(view string)
{{- end }}
}
{{- end }}
`
const payloadT = `{{ comment .PayloadDesc }}
type {{ .Payload }} {{ .PayloadDef }}
`
const streamingPayloadT = `{{ comment .StreamingPayloadDesc }}
type {{ .StreamingPayload }} {{ .StreamingPayloadDef }}
`
const resultT = `{{ comment .ResultDesc }}
type {{ .Result }} {{ .ResultDef }}
`
const userTypeT = `{{ comment .Description }}
type {{ .VarName }} {{ .Def }}
`
const errorT = `// Error returns an error description.
func (e {{ .Ref }}) Error() string {
return {{ printf "%q" .Description }}
}
// ErrorName returns {{ printf "%q" .Name }}.
func (e {{ .Ref }}) ErrorName() string {
return {{ errorName . }}
}
`
// input: map[string]{"Type": TypeData, "Error": ErrorData}
const errorInitT = `{{ printf "%s builds a %s from an error." .Name .TypeName | comment }}
func {{ .Name }}(err error) {{ .TypeRef }} {
return &{{ .TypeName }}{
Name: {{ printf "%q" .ErrName }},
ID: goa.NewErrorID(),
Message: err.Error(),
{{- if .Temporary }}
Temporary: true,
{{- end }}
{{- if .Timeout }}
Timeout: true,
{{- end }}
{{- if .Fault }}
Fault: true,
{{- end }}
}
}
`
// input: InitData
const typeInitT = `{{ comment .Description }}
func {{ .Name }}({{ range .Args }}{{ .Name }} {{ .Ref }}, {{ end }}) {{ .ReturnTypeRef }} {
{{ .Code }}
}
`