-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
resolver.go
514 lines (443 loc) · 15.3 KB
/
resolver.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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// Copyright 2022 Dave Shanley / Quobix
// SPDX-License-Identifier: MIT
package resolver
import (
"fmt"
"github.com/pb33f/libopenapi/index"
"github.com/pb33f/libopenapi/utils"
"gopkg.in/yaml.v3"
)
// ResolvingError represents an issue the resolver had trying to stitch the tree together.
type ResolvingError struct {
// ErrorRef is the error thrown by the resolver
ErrorRef error
// Node is the *yaml.Node reference that contains the resolving error
Node *yaml.Node
// Path is the shortened journey taken by the resolver
Path string
// CircularReference is set if the error is a reference to the circular reference.
CircularReference *index.CircularReferenceResult
}
func (r *ResolvingError) Error() string {
return fmt.Sprintf("%s: %s [%d:%d]", r.ErrorRef.Error(),
r.Path, r.Node.Line, r.Node.Column)
}
// Resolver will use a *index.SpecIndex to stitch together a resolved root tree using all the discovered
// references in the doc.
type Resolver struct {
specIndex *index.SpecIndex
resolvedRoot *yaml.Node
resolvingErrors []*ResolvingError
circularReferences []*index.CircularReferenceResult
referencesVisited int
indexesVisited int
journeysTaken int
relativesSeen int
ignorePoly bool
ignoreArray bool
}
// NewResolver will create a new resolver from a *index.SpecIndex
func NewResolver(index *index.SpecIndex) *Resolver {
if index == nil {
return nil
}
return &Resolver{
specIndex: index,
resolvedRoot: index.GetRootNode(),
}
}
// GetResolvingErrors returns all errors found during resolving
func (resolver *Resolver) GetResolvingErrors() []*ResolvingError {
return resolver.resolvingErrors
}
// GetCircularErrors returns all circular reference errors found.
func (resolver *Resolver) GetCircularErrors() []*index.CircularReferenceResult {
return resolver.circularReferences
}
// GetPolymorphicCircularErrors returns all circular errors that stem from polymorphism
func (resolver *Resolver) GetPolymorphicCircularErrors() []*index.CircularReferenceResult {
var res []*index.CircularReferenceResult
for i := range resolver.circularReferences {
if !resolver.circularReferences[i].IsInfiniteLoop {
continue
}
if !resolver.circularReferences[i].IsPolymorphicResult {
continue
}
res = append(res, resolver.circularReferences[i])
}
return res
}
// GetNonPolymorphicCircularErrors returns all circular errors that DO NOT stem from polymorphism
func (resolver *Resolver) GetNonPolymorphicCircularErrors() []*index.CircularReferenceResult {
var res []*index.CircularReferenceResult
for i := range resolver.circularReferences {
if !resolver.circularReferences[i].IsInfiniteLoop {
continue
}
if !resolver.circularReferences[i].IsPolymorphicResult {
res = append(res, resolver.circularReferences[i])
}
}
return res
}
// IgnorePolymorphicCircularReferences will ignore any circular references that are polymorphic (oneOf, anyOf, allOf)
// This must be set before any resolving is done.
func (resolver *Resolver) IgnorePolymorphicCircularReferences() {
resolver.ignorePoly = true
}
// IgnoreArrayCircularReferences will ignore any circular references that stem from arrays. This must be set before
// any resolving is done.
func (resolver *Resolver) IgnoreArrayCircularReferences() {
resolver.ignoreArray = true
}
// GetJourneysTaken returns the number of journeys taken by the resolver
func (resolver *Resolver) GetJourneysTaken() int {
return resolver.journeysTaken
}
// GetReferenceVisited returns the number of references visited by the resolver
func (resolver *Resolver) GetReferenceVisited() int {
return resolver.referencesVisited
}
// GetIndexesVisited returns the number of indexes visited by the resolver
func (resolver *Resolver) GetIndexesVisited() int {
return resolver.indexesVisited
}
// GetRelativesSeen returns the number of siblings (nodes at the same level) seen for each reference found.
func (resolver *Resolver) GetRelativesSeen() int {
return resolver.relativesSeen
}
// Resolve will resolve the specification, everything that is not polymorphic and not circular, will be resolved.
// this data can get big, it results in a massive duplication of data. This is a destructive method and will permanently
// re-organize the node tree. Make sure you have copied your original tree before running this (if you want to preserve
// original data)
func (resolver *Resolver) Resolve() []*ResolvingError {
visitIndex(resolver, resolver.specIndex)
for _, circRef := range resolver.circularReferences {
// If the circular reference is not required, we can ignore it, as it's a terminable loop rather than an infinite one
if !circRef.IsInfiniteLoop {
continue
}
resolver.resolvingErrors = append(resolver.resolvingErrors, &ResolvingError{
ErrorRef: fmt.Errorf("Infinite circular reference detected: %s", circRef.Start.Name),
Node: circRef.LoopPoint.Node,
Path: circRef.GenerateJourneyPath(),
})
}
return resolver.resolvingErrors
}
// CheckForCircularReferences Check for circular references, without resolving, a non-destructive run.
func (resolver *Resolver) CheckForCircularReferences() []*ResolvingError {
visitIndexWithoutDamagingIt(resolver, resolver.specIndex)
for _, circRef := range resolver.circularReferences {
// If the circular reference is not required, we can ignore it, as it's a terminable loop rather than an infinite one
if !circRef.IsInfiniteLoop {
continue
}
resolver.resolvingErrors = append(resolver.resolvingErrors, &ResolvingError{
ErrorRef: fmt.Errorf("Infinite circular reference detected: %s", circRef.Start.Name),
Node: circRef.LoopPoint.Node,
Path: circRef.GenerateJourneyPath(),
CircularReference: circRef,
})
}
// update our index with any circular refs we found.
resolver.specIndex.SetCircularReferences(resolver.circularReferences)
return resolver.resolvingErrors
}
func visitIndexWithoutDamagingIt(res *Resolver, idx *index.SpecIndex) {
mapped := idx.GetMappedReferencesSequenced()
mappedIndex := idx.GetMappedReferences()
res.indexesVisited++
for _, ref := range mapped {
seenReferences := make(map[string]bool)
var journey []*index.Reference
res.journeysTaken++
res.VisitReference(ref.Reference, seenReferences, journey, false)
}
schemas := idx.GetAllComponentSchemas()
for s, schemaRef := range schemas {
if mappedIndex[s] == nil {
seenReferences := make(map[string]bool)
var journey []*index.Reference
res.journeysTaken++
res.VisitReference(schemaRef, seenReferences, journey, false)
}
}
for _, c := range idx.GetChildren() {
visitIndexWithoutDamagingIt(res, c)
}
}
func visitIndex(res *Resolver, idx *index.SpecIndex) {
mapped := idx.GetMappedReferencesSequenced()
mappedIndex := idx.GetMappedReferences()
res.indexesVisited++
for _, ref := range mapped {
seenReferences := make(map[string]bool)
var journey []*index.Reference
res.journeysTaken++
if ref != nil && ref.Reference != nil {
ref.Reference.Node.Content = res.VisitReference(ref.Reference, seenReferences, journey, true)
}
}
schemas := idx.GetAllComponentSchemas()
for s, schemaRef := range schemas {
if mappedIndex[s] == nil {
seenReferences := make(map[string]bool)
var journey []*index.Reference
res.journeysTaken++
schemaRef.Node.Content = res.VisitReference(schemaRef, seenReferences, journey, true)
}
}
// map everything
for _, sequenced := range idx.GetAllSequencedReferences() {
locatedDef := mappedIndex[sequenced.Definition]
if locatedDef != nil {
if !locatedDef.Circular && locatedDef.Seen {
sequenced.Node.Content = locatedDef.Node.Content
}
}
}
for _, c := range idx.GetChildren() {
visitIndex(res, c)
}
}
// VisitReference will visit a reference as part of a journey and will return resolved nodes.
func (resolver *Resolver) VisitReference(ref *index.Reference, seen map[string]bool, journey []*index.Reference, resolve bool) []*yaml.Node {
resolver.referencesVisited++
if ref.Resolved || ref.Seen {
return ref.Node.Content
}
journey = append(journey, ref)
relatives := resolver.extractRelatives(ref.Node, nil, seen, journey, resolve)
seen = make(map[string]bool)
seen[ref.Definition] = true
for _, r := range relatives {
// check if we have seen this on the journey before, if so! it's circular
skip := false
for i, j := range journey {
if j.Definition == r.Definition {
var foundDup *index.Reference
foundRefs := resolver.specIndex.SearchIndexForReference(r.Definition)
if len(foundRefs) > 0 {
foundDup = foundRefs[0]
}
var circRef *index.CircularReferenceResult
if !foundDup.Circular {
loop := append(journey, foundDup)
visitedDefinitions := map[string]bool{}
isInfiniteLoop, _ := resolver.isInfiniteCircularDependency(foundDup, visitedDefinitions, nil)
isArray := false
if r.ParentNodeSchemaType == "array" {
isArray = true
}
circRef = &index.CircularReferenceResult{
Journey: loop,
Start: foundDup,
LoopIndex: i,
LoopPoint: foundDup,
IsArrayResult: isArray,
IsInfiniteLoop: isInfiniteLoop,
}
resolver.circularReferences = append(resolver.circularReferences, circRef)
foundDup.Seen = true
foundDup.Circular = true
}
skip = true
}
}
if !skip {
var original *index.Reference
foundRefs := resolver.specIndex.SearchIndexForReference(r.Definition)
if len(foundRefs) > 0 {
original = foundRefs[0]
}
resolved := resolver.VisitReference(original, seen, journey, resolve)
if resolve {
r.Node.Content = resolved // this is where we perform the actual resolving.
}
r.Seen = true
ref.Seen = true
}
}
ref.Resolved = true
ref.Seen = true
return ref.Node.Content
}
func (resolver *Resolver) isInfiniteCircularDependency(ref *index.Reference, visitedDefinitions map[string]bool, initialRef *index.Reference) (bool, map[string]bool) {
if ref == nil {
return false, visitedDefinitions
}
for refDefinition := range ref.RequiredRefProperties {
r := resolver.specIndex.GetMappedReferences()[refDefinition]
if initialRef != nil && initialRef.Definition == r.Definition {
return true, visitedDefinitions
}
if visitedDefinitions[r.Definition] {
continue
}
visitedDefinitions[r.Definition] = true
ir := initialRef
if ir == nil {
ir = ref
}
var isChildICD bool
isChildICD, visitedDefinitions = resolver.isInfiniteCircularDependency(r, visitedDefinitions, ir)
if isChildICD {
return true, visitedDefinitions
}
}
return false, visitedDefinitions
}
func (resolver *Resolver) extractRelatives(node, parent *yaml.Node,
foundRelatives map[string]bool,
journey []*index.Reference, resolve bool) []*index.Reference {
if len(journey) > 100 {
return nil
}
var found []*index.Reference
if len(node.Content) > 0 {
for i, n := range node.Content {
if utils.IsNodeMap(n) || utils.IsNodeArray(n) {
var anyvn, allvn, onevn, arrayTypevn *yaml.Node
// extract polymorphic references
if len(n.Content) > 1 {
_, anyvn = utils.FindKeyNodeTop("anyOf", n.Content)
_, allvn = utils.FindKeyNodeTop("allOf", n.Content)
_, onevn = utils.FindKeyNodeTop("oneOf", n.Content)
_, arrayTypevn = utils.FindKeyNodeTop("type", n.Content)
}
if anyvn != nil || allvn != nil || onevn != nil {
if resolver.ignorePoly {
continue
}
}
if arrayTypevn != nil {
if arrayTypevn.Value == "array" {
if resolver.ignoreArray {
continue
}
}
}
found = append(found, resolver.extractRelatives(n, node, foundRelatives, journey, resolve)...)
}
if i%2 == 0 && n.Value == "$ref" {
if !utils.IsNodeStringValue(node.Content[i+1]) {
continue
}
value := node.Content[i+1].Value
ref := resolver.specIndex.SearchIndexForReference(value)
if ref == nil {
_, path := utils.ConvertComponentIdIntoFriendlyPathSearch(value)
err := &ResolvingError{
ErrorRef: fmt.Errorf("cannot resolve reference `%s`, it's missing", value),
Node: n,
Path: path,
}
resolver.resolvingErrors = append(resolver.resolvingErrors, err)
continue
}
schemaType := ""
if parent != nil {
_, arrayTypevn := utils.FindKeyNodeTop("type", parent.Content)
if arrayTypevn != nil {
if arrayTypevn.Value == "array" {
schemaType = "array"
}
}
}
r := &index.Reference{
Definition: value,
Name: value,
Node: node,
ParentNode: parent,
ParentNodeSchemaType: schemaType,
}
found = append(found, r)
foundRelatives[value] = true
}
if i%2 == 0 && n.Value != "$ref" && n.Value != "" {
if n.Value == "allOf" ||
n.Value == "oneOf" ||
n.Value == "anyOf" {
// if this is a polymorphic link, we want to follow it and see if it becomes circular
if utils.IsNodeMap(node.Content[i+1]) { // check for nested items
// check if items is present, to indicate an array
if _, v := utils.FindKeyNodeTop("items", node.Content[i+1].Content); v != nil {
if utils.IsNodeMap(v) {
if d, _, l := utils.IsNodeRefValue(v); d {
ref := resolver.specIndex.GetMappedReferences()[l]
if ref != nil && !ref.Circular {
circ := false
for f := range journey {
if journey[f].Definition == ref.Definition {
circ = true
break
}
}
if !circ {
resolver.VisitReference(ref, foundRelatives, journey, resolve)
} else {
loop := append(journey, ref)
circRef := &index.CircularReferenceResult{
Journey: loop,
Start: ref,
LoopIndex: i,
LoopPoint: ref,
PolymorphicType: n.Value,
IsPolymorphicResult: true,
}
ref.Seen = true
ref.Circular = true
resolver.circularReferences = append(resolver.circularReferences, circRef)
}
}
}
}
}
}
// for array based polymorphic items
if utils.IsNodeArray(node.Content[i+1]) { // check for nested items
// check if items is present, to indicate an array
for q := range node.Content[i+1].Content {
v := node.Content[i+1].Content[q]
if utils.IsNodeMap(v) {
if d, _, l := utils.IsNodeRefValue(v); d {
ref := resolver.specIndex.GetMappedReferences()[l]
if ref != nil && !ref.Circular {
circ := false
for f := range journey {
if journey[f].Definition == ref.Definition {
circ = true
break
}
}
if !circ {
resolver.VisitReference(ref, foundRelatives, journey, resolve)
} else {
loop := append(journey, ref)
circRef := &index.CircularReferenceResult{
Journey: loop,
Start: ref,
LoopIndex: i,
LoopPoint: ref,
PolymorphicType: n.Value,
IsPolymorphicResult: true,
}
ref.Seen = true
ref.Circular = true
resolver.circularReferences = append(resolver.circularReferences, circRef)
}
}
}
}
}
}
break
}
}
}
}
resolver.relativesSeen += len(found)
return found
}