-
Notifications
You must be signed in to change notification settings - Fork 37
/
package.go
435 lines (407 loc) · 11.1 KB
/
package.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
433
434
435
// Package holds higher-level abstractions on top of OpenAPI that are used
// to generate code via text/template for Databricks SDK in different languages.
package code
import (
"context"
"fmt"
"regexp"
"sort"
"strings"
"github.com/databricks/databricks-sdk-go/logger"
"github.com/databricks/databricks-sdk-go/openapi"
)
// Package represents a service package, which contains entities and interfaces
// that are relevant to a single service
type Package struct {
Named
Components *openapi.Components
services map[string]*Service
types map[string]*Entity
extImports map[string]*Entity
}
// FullName just returns pacakge name
func (pkg *Package) FullName() string {
return pkg.CamelName()
}
// Services returns sorted slice of services
func (pkg *Package) Services() (types []*Service) {
for _, v := range pkg.services {
types = append(types, v)
}
pascalNameSort(types)
return types
}
func (pkg *Package) addRecursively(service *Service, result []*Service) []*Service {
result = append(result, service)
subservices := make([]*Service, 0, len(service.subservices))
for _, v := range service.subservices {
subservices = append(subservices, v)
}
pascalNameSort(subservices)
for _, svc := range subservices {
result = pkg.addRecursively(svc, result)
}
return result
}
// Returns the Services sorted such has parents always come before subservices.
func (pkg *Package) ServicesSortedByParent() []*Service {
allServices := pkg.Services()
resultServices := []*Service{}
for _, svc := range allServices {
if svc.ParentService != nil {
continue
}
resultServices = pkg.addRecursively(svc, resultServices)
}
return resultServices
}
// MainService returns a Service that matches Package name
func (pkg *Package) MainService() *Service {
for _, svc := range pkg.services {
if !svc.MatchesPackageName() {
continue
}
return svc
}
return nil
}
// Types returns sorted slice of types
func (pkg *Package) Types() (types []*Entity) {
for _, v := range pkg.types {
types = append(types, v)
}
pascalNameSort(types)
return types
}
// HasPagination returns try if any service within this package has result
// iteration
func (pkg *Package) HasPagination() bool {
for _, v := range pkg.services {
if v.HasPagination() {
return true
}
}
return false
}
func (pkg *Package) ImportedEntities() (res []*Entity) {
for _, e := range pkg.extImports {
res = append(res, e)
}
fullNameSort(res)
return
}
func (pkg *Package) ImportedPackages() (res []string) {
tmp := map[string]bool{}
for _, e := range pkg.extImports {
tmp[e.Package.Name] = true
}
for name := range tmp {
res = append(res, name)
}
sort.Strings(res)
return
}
// schemaToEntity converts a schema into an Entity
// processedEntities keeps track of the entities that are being generated to avoid infinite recursion.
func (pkg *Package) schemaToEntity(s *openapi.Schema, path []string, hasName bool, processedEntities map[string]*Entity) *Entity {
if s.IsRef() {
pair := strings.Split(s.Component(), ".")
if len(pair) == 2 && pair[0] != pkg.Name {
schemaPackage := pair[0]
schemaType := pair[1]
if pkg.extImports == nil {
pkg.extImports = map[string]*Entity{}
}
known, ok := pkg.extImports[s.Component()]
if ok {
return known
}
// referred entity is declared in another package
pkg.extImports[s.Component()] = &Entity{
Named: Named{
Name: schemaType,
},
Package: &Package{
Named: Named{
Name: schemaPackage,
},
},
}
return pkg.extImports[s.Component()]
}
// if schema is src, load it to this package
src := pkg.Components.Schemas.Resolve(s)
if src == nil {
return nil
}
component := pkg.localComponent(&s.Node)
return pkg.definedEntity(component, *src, processedEntities)
}
e := &Entity{
Named: Named{
Description: s.Description,
},
Schema: s,
Package: pkg,
enum: map[string]EnumEntry{},
}
if s.JsonPath != "" {
processedEntities[s.JsonPath] = e
}
// pull embedded types up, if they can be defined at package level
if s.IsDefinable() && !hasName {
// TODO: log message or panic when overrides a type
e.Named.Name = strings.Join(path, "")
pkg.define(e)
}
e.fields = map[string]*Field{}
e.IsAny = s.IsAny
e.IsComputed = s.IsComputed
e.RequiredOrder = s.Required
// enum
if len(s.Enum) != 0 {
return pkg.makeEnum(e, s, path)
}
// object
if len(s.Properties) != 0 {
return pkg.makeObject(e, s, path, processedEntities)
}
// array
if s.ArrayValue != nil {
e.ArrayValue = pkg.schemaToEntity(s.ArrayValue, append(path, "Item"), false, processedEntities)
return e
}
// map
if s.MapValue != nil {
e.MapValue = pkg.schemaToEntity(s.MapValue, path, hasName, processedEntities)
return e
}
e.IsBool = s.Type == "boolean" || s.Type == "bool"
e.IsString = s.Type == "string"
e.IsInt64 = s.Type == "integer" && s.Format == "int64"
e.IsFloat64 = s.Type == "number" && s.Format == "double"
e.IsInt = s.Type == "integer" || s.Type == "int"
return e
}
// makeObject converts OpenAPI Schema into type representation
// processedEntities keeps track of the entities that are being generated to avoid infinite recursion.
func (pkg *Package) makeObject(e *Entity, s *openapi.Schema, path []string, processedEntities map[string]*Entity) *Entity {
required := map[string]bool{}
for _, v := range s.Required {
required[v] = true
}
for k, v := range s.Properties {
if v.Description == "" && v.IsRef() {
vv := pkg.Components.Schemas.Resolve(v)
if vv != nil {
v.Description = (*vv).Description
}
}
named := Named{k, v.Description}
e.fields[k] = &Field{
Named: named,
Entity: pkg.schemaToEntity(v, append(path, named.PascalName()), false, processedEntities),
Required: required[k],
Schema: v,
IsJson: true,
}
}
pkg.updateType(e)
return e
}
var whitespace = regexp.MustCompile(`\s+`)
func (pkg *Package) makeEnum(e *Entity, s *openapi.Schema, path []string) *Entity {
for idx, content := range s.Enum {
name := content
if len(s.AliasEnum) == len(s.Enum) {
name = s.AliasEnum[idx]
}
description := s.EnumDescriptions[content]
e.enum[content] = EnumEntry{
Named: Named{name, description},
Entity: e,
Content: content,
}
}
return e
}
func (pkg *Package) localComponent(n *openapi.Node) string {
component := n.Component()
if strings.HasPrefix(component, pkg.Name+".") {
component = strings.ReplaceAll(component, pkg.Name+".", "")
}
return component
}
// definedEntity defines and returns the requested entity based on the schema.
// processedEntities keeps track of the entities that are being generated to avoid infinite recursion.
func (pkg *Package) definedEntity(name string, s *openapi.Schema, processedEntities map[string]*Entity) *Entity {
if s == nil {
entity := &Entity{
Named: Named{
Name: name,
Description: "",
},
fields: map[string]*Field{},
}
return pkg.define(entity)
}
if entity, ok := processedEntities[s.JsonPath]; ok {
// Return existing entity if it's already being generated.
return entity
}
e := pkg.schemaToEntity(s, []string{name}, true, processedEntities)
if e == nil {
// gets here when responses are objects with no properties
return nil
}
if e.ArrayValue != nil {
return e
}
if e.Name == "" {
e.Named = Named{name, s.Description}
}
return pkg.define(e)
}
func (pkg *Package) define(entity *Entity) *Entity {
k := entity.PascalName()
_, defined := pkg.types[k]
if defined {
//panic(fmt.Sprintf("%s is already defined", entity.Name))
return entity
}
if entity.Package == nil {
entity.Package = pkg
}
pkg.types[k] = entity
return entity
}
func (pkg *Package) updateType(entity *Entity) {
e, defined := pkg.types[entity.PascalName()]
if !defined {
return
}
for k, v := range entity.fields {
e.fields[k] = v
}
}
// HasPathParams returns true if any service has methods that rely on path params
func (pkg *Package) HasPathParams() bool {
for _, s := range pkg.services {
for _, m := range s.methods {
if len(m.PathParts) > 0 {
return true
}
}
}
return false
}
// HasWaits returns true if any service has methods with long-running operations
func (pkg *Package) HasWaits() bool {
for _, s := range pkg.services {
for _, m := range s.methods {
if m.wait != nil {
return true
}
}
}
return false
}
func (pkg *Package) getService(tag *openapi.Tag) *Service {
svc, ok := pkg.services[tag.Service]
if !ok {
svc = &Service{
Package: pkg,
IsAccounts: tag.IsAccounts,
PathStyle: tag.PathStyle,
methods: map[string]*Method{},
subservices: map[string]*Service{},
Named: Named{
Name: tag.Service,
Description: tag.Description,
},
tag: tag,
}
pkg.services[tag.Service] = svc
}
return svc
}
// Load takes OpenAPI specification and loads a service model
func (pkg *Package) Load(ctx context.Context, spec *openapi.Specification, tag openapi.Tag) error {
svc := pkg.getService(&tag)
for k, v := range spec.Components.Schemas {
split := strings.Split(k, ".")
if split[0] != pkg.Name {
continue
}
pkg.definedEntity(split[1], *v, map[string]*Entity{})
}
// Fill in subservice information
if tag.ParentService != "" {
parentTag, err := spec.GetTagByServiceName(tag.ParentService)
if err != nil {
return err
}
parentSvc := pkg.getService(parentTag)
parentSvc.subservices[svc.Name] = svc
svc.ParentService = parentSvc
}
for prefix, path := range spec.Paths {
for verb, op := range path.Verbs() {
if op.OperationId == "Files.getStatusHead" {
// skip this method, it needs to be removed from the spec
continue
}
if !op.HasTag(tag.Name) {
continue
}
logger.Infof(ctx, "pkg.Load %s %s", verb, prefix)
params := []openapi.Parameter{}
seenParams := map[string]bool{}
for _, list := range [][]openapi.Parameter{path.Parameters, op.Parameters} {
for _, v := range list {
param, err := pkg.resolveParam(&v)
if err != nil {
return fmt.Errorf("could not resolve parameter %s for %s %s. This could be due to a problem in the definition of this parameter. If using $ref, ensure that $ref is used inside the 'schema' keyword", v.Name, verb, prefix)
}
if param == nil {
return nil
}
// We don't support headers in requests.
if param.In == "header" {
continue
}
// do not propagate common path parameter to account-level APIs
if svc.IsAccounts && param.In == "path" && param.Name == "account_id" {
continue
}
if seenParams[param.Name] {
continue
}
if prefix == "/api/2.0/workspace/export" && param.Name == "direct_download" {
// prevent changing the response content type via request parameter
// https://github.com/databricks/databricks-sdk-py/issues/104
continue
}
params = append(params, *param)
seenParams[param.Name] = true
}
}
method, err := svc.newMethod(verb, prefix, params, op)
if err != nil {
return err
}
svc.methods[method.Name] = method
}
}
return nil
}
func (pkg *Package) resolveParam(v *openapi.Parameter) (param *openapi.Parameter, err error) {
defer func() {
r := recover()
if r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
param = *pkg.Components.Parameters.Resolve(v)
return
}