-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathreference.go
More file actions
708 lines (603 loc) · 23.4 KB
/
reference.go
File metadata and controls
708 lines (603 loc) · 23.4 KB
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
package openapi
import (
"context"
"errors"
"fmt"
"strings"
"sync"
"github.com/speakeasy-api/openapi/internal/interfaces"
"github.com/speakeasy-api/openapi/internal/utils"
"github.com/speakeasy-api/openapi/marshaller"
"github.com/speakeasy-api/openapi/openapi/core"
"github.com/speakeasy-api/openapi/pointer"
"github.com/speakeasy-api/openapi/references"
"github.com/speakeasy-api/openapi/validation"
"gopkg.in/yaml.v3"
)
type (
// ReferencedPathItem represents a path item that can either be referenced from elsewhere or declared inline.
ReferencedPathItem = Reference[PathItem, *PathItem, *core.PathItem]
// ReferencedExample represents an example that can either be referenced from elsewhere or declared inline.
ReferencedExample = Reference[Example, *Example, *core.Example]
// ReferencedParameter represents a parameter that can either be referenced from elsewhere or declared inline.
ReferencedParameter = Reference[Parameter, *Parameter, *core.Parameter]
// ReferencedHeader represents a header that can either be referenced from elsewhere or declared inline.
ReferencedHeader = Reference[Header, *Header, *core.Header]
// ReferencedRequestBody represents a request body that can either be referenced from elsewhere or declared inline.
ReferencedRequestBody = Reference[RequestBody, *RequestBody, *core.RequestBody]
// ReferencedCallback represents a callback that can either be referenced from elsewhere or declared inline.
ReferencedCallback = Reference[Callback, *Callback, *core.Callback]
// ReferencedResponse represents a response that can either be referenced from elsewhere or declared inline.
ReferencedResponse = Reference[Response, *Response, *core.Response]
// ReferencedLink represents a link that can either be referenced from elsewhere or declared inline.
ReferencedLink = Reference[Link, *Link, *core.Link]
// ReferencedSecurityScheme represents a security scheme that can either be referenced from elsewhere or declared inline.
ReferencedSecurityScheme = Reference[SecurityScheme, *SecurityScheme, *core.SecurityScheme]
)
// NewReferencedPathItemFromRef creates a new ReferencedPathItem from a reference.
func NewReferencedPathItemFromRef(ref references.Reference) *ReferencedPathItem {
return &ReferencedPathItem{
Reference: &ref,
}
}
// NewReferencedPathItemFromPathItem creates a new ReferencedPathItem from a PathItem.
func NewReferencedPathItemFromPathItem(pathItem *PathItem) *ReferencedPathItem {
return &ReferencedPathItem{
Object: pathItem,
}
}
// NewReferencedExampleFromRef creates a new ReferencedExample from a reference.
func NewReferencedExampleFromRef(ref references.Reference) *ReferencedExample {
return &ReferencedExample{
Reference: &ref,
}
}
// NewReferencedExampleFromExample creates a new ReferencedExample from an Example.
func NewReferencedExampleFromExample(example *Example) *ReferencedExample {
return &ReferencedExample{
Object: example,
}
}
// NewReferencedParameterFromRef creates a new ReferencedParameter from a reference.
func NewReferencedParameterFromRef(ref references.Reference) *ReferencedParameter {
return &ReferencedParameter{
Reference: &ref,
}
}
// NewReferencedParameterFromParameter creates a new ReferencedParameter from a Parameter.
func NewReferencedParameterFromParameter(parameter *Parameter) *ReferencedParameter {
return &ReferencedParameter{
Object: parameter,
}
}
// NewReferencedHeaderFromRef creates a new ReferencedHeader from a reference.
func NewReferencedHeaderFromRef(ref references.Reference) *ReferencedHeader {
return &ReferencedHeader{
Reference: &ref,
}
}
// NewReferencedHeaderFromHeader creates a new ReferencedHeader from a Header.
func NewReferencedHeaderFromHeader(header *Header) *ReferencedHeader {
return &ReferencedHeader{
Object: header,
}
}
// NewReferencedRequestBodyFromRef creates a new ReferencedRequestBody from a reference.
func NewReferencedRequestBodyFromRef(ref references.Reference) *ReferencedRequestBody {
return &ReferencedRequestBody{
Reference: &ref,
}
}
// NewReferencedRequestBodyFromRequestBody creates a new ReferencedRequestBody from a RequestBody.
func NewReferencedRequestBodyFromRequestBody(requestBody *RequestBody) *ReferencedRequestBody {
return &ReferencedRequestBody{
Object: requestBody,
}
}
// NewReferencedResponseFromRef creates a new ReferencedResponse from a reference.
func NewReferencedResponseFromRef(ref references.Reference) *ReferencedResponse {
return &ReferencedResponse{
Reference: &ref,
}
}
// NewReferencedResponseFromResponse creates a new ReferencedResponse from a Response.
func NewReferencedResponseFromResponse(response *Response) *ReferencedResponse {
return &ReferencedResponse{
Object: response,
}
}
// NewReferencedCallbackFromRef creates a new ReferencedCallback from a reference.
func NewReferencedCallbackFromRef(ref references.Reference) *ReferencedCallback {
return &ReferencedCallback{
Reference: &ref,
}
}
// NewReferencedCallbackFromCallback creates a new ReferencedCallback from a Callback.
func NewReferencedCallbackFromCallback(callback *Callback) *ReferencedCallback {
return &ReferencedCallback{
Object: callback,
}
}
// NewReferencedLinkFromRef creates a new ReferencedLink from a reference.
func NewReferencedLinkFromRef(ref references.Reference) *ReferencedLink {
return &ReferencedLink{
Reference: &ref,
}
}
// NewReferencedLinkFromLink creates a new ReferencedLink from a Link.
func NewReferencedLinkFromLink(link *Link) *ReferencedLink {
return &ReferencedLink{
Object: link,
}
}
// NewReferencedSecuritySchemeFromRef creates a new ReferencedSecurityScheme from a reference.
func NewReferencedSecuritySchemeFromRef(ref references.Reference) *ReferencedSecurityScheme {
return &ReferencedSecurityScheme{
Reference: &ref,
}
}
// NewReferencedSecuritySchemeFromSecurityScheme creates a new ReferencedSecurityScheme from a SecurityScheme.
func NewReferencedSecuritySchemeFromSecurityScheme(securityScheme *SecurityScheme) *ReferencedSecurityScheme {
return &ReferencedSecurityScheme{
Object: securityScheme,
}
}
type ReferencedObject[T any] interface {
IsReference() bool
GetObject() *T
}
type Reference[T any, V interfaces.Validator[T], C marshaller.CoreModeler] struct {
marshaller.Model[core.Reference[C]]
// Reference is the URI to the
Reference *references.Reference
// A short summary of the referenced object. Should override any summary provided in the referenced object.
Summary *string
// A longer description of the referenced object. Should override any description provided in the referenced object.
Description *string
// If this was an inline object instead of a reference this will contain that object.
Object *T
// Mutex to protect concurrent access to cache fields (pointers to allow struct copying)
cacheMutex *sync.RWMutex
initMutex *sync.Once
referenceResolutionCache *references.ResolveResult[Reference[T, V, C]]
validationErrsCache []error
circularErrorFound bool
// Parent reference links - private fields to avoid serialization
// These are set when the reference was resolved via a reference chain.
//
// Parent links are only set if this reference was accessed through reference resolution.
// If you access a reference directly (e.g., by iterating through a document's components),
// these will be nil even if the reference could be referenced elsewhere.
//
// Example scenarios when parent links are set:
// - Single reference: main.yaml#/components/parameters/Param -> Parameter object
// parent = nil, topLevelParent = nil (this is the original reference)
// - Chained reference: main.yaml -> external.yaml#/Param -> final Parameter object
// For the intermediate reference: parent = original reference, topLevelParent = original reference
// For the final resolved object: parent links are set during resolution
parent *Reference[T, V, C] // Immediate parent reference in the chain
topLevelParent *Reference[T, V, C] // Top-level parent (root of the reference chain)
}
var _ references.Resolvable[Info] = (*Reference[Info, *Info, *core.Info])(nil)
var _ interfaces.Model[core.Reference[*core.Info]] = (*Reference[Info, *Info, *core.Info])(nil)
// ResolveOptions represent the options available when resolving a reference.
type ResolveOptions = references.ResolveOptions
// Resolve will fully resolve the reference. This will recursively resolve any intermediate references as well. Will return errors if there is a circular reference issue.
// Validation errors can be skipped by setting the skipValidation flag to true. This will skip the missing field errors that occur during unmarshaling.
// Resolution doesn't run the Validate function on the resolved object. So if you want to fully validate the object after resolution, you need to call the Validate function manually.
func (r *Reference[T, V, C]) Resolve(ctx context.Context, opts ResolveOptions) ([]error, error) {
if r == nil {
return nil, nil
}
targetDocument := opts.TargetDocument
if targetDocument == nil {
targetDocument = opts.RootDocument
}
return resolveObjectWithTracking(ctx, r, references.ResolveOptions{
RootDocument: opts.RootDocument,
TargetLocation: opts.TargetLocation,
TargetDocument: targetDocument,
DisableExternalRefs: opts.DisableExternalRefs,
VirtualFS: opts.VirtualFS,
HTTPClient: opts.HTTPClient,
}, []string{})
}
// IsReference returns true if the reference is a reference (via $ref) to an object as opposed to an inline object.
func (r *Reference[T, V, C]) IsReference() bool {
if r == nil {
return false
}
return r.Reference != nil
}
// IsResolved returns true if the reference is resolved (not a reference or the reference has been resolved)
func (r *Reference[T, V, C]) IsResolved() bool {
if r == nil {
return false
}
if !r.IsReference() {
return true
}
r.ensureMutex()
r.cacheMutex.RLock()
defer r.cacheMutex.RUnlock()
return (r.referenceResolutionCache != nil && r.referenceResolutionCache.Object != nil) || r.circularErrorFound
}
// GetReference returns the value of the Reference field. Returns empty string if not set.
func (r *Reference[T, V, C]) GetReference() references.Reference {
if r == nil || r.Reference == nil {
return ""
}
return *r.Reference
}
// GetResolvedObject will return the referenced object. If this is a reference and its unresolved, this will return nil.
// This methods is identical to GetObject but was added to support the Resolvable interface
func (r *Reference[T, V, C]) GetResolvedObject() *T {
if r == nil {
return nil
}
return r.GetObject()
}
// GetObject returns the referenced object. If this is a reference and its unresolved, this will return nil.
// This methods is identical to GetResolvedObject but was kept for backwards compatibility
func (r *Reference[T, V, C]) GetObject() *T {
if r == nil {
return nil
}
if !r.IsReference() {
return r.Object
}
r.ensureMutex()
r.cacheMutex.RLock()
defer r.cacheMutex.RUnlock()
if (r.referenceResolutionCache != nil && r.referenceResolutionCache.Object != nil) || r.circularErrorFound {
if r.referenceResolutionCache != nil && r.referenceResolutionCache.Object != nil {
return r.referenceResolutionCache.Object.GetObject()
}
}
return nil
}
// MustGetObject will return the referenced object. If this is a reference and its unresolved, this will panic.
// Useful if references have been resolved before hand.
func (r *Reference[T, V, C]) MustGetObject() *T {
if r == nil {
return nil
}
obj := r.GetObject()
if r.IsReference() && obj == nil {
panic("unresolved reference, resolve first")
}
return obj
}
// GetObjectAny returns the referenced object. If this is a reference and its unresolved, this will return nil.
// This is a convenience method for use with the various reflection based utility functions.
func (r *Reference[T, V, C]) GetObjectAny() any {
if r == nil {
return nil
}
return r.GetObject()
}
// GetSummary returns the value of the Summary field. Returns empty string if not set.
func (r *Reference[T, V, C]) GetSummary() string {
if r == nil || r.Summary == nil {
return ""
}
return *r.Summary
}
// GetDescription returns the value of the Description field. Returns empty string if not set.
func (r *Reference[T, V, C]) GetDescription() string {
if r == nil || r.Description == nil {
return ""
}
return *r.Description
}
// GetRootNode returns the root YAML node of the referenced object if it exists.
// Returns nil if the object is not resolved or doesn't have a root node.
func (r *Reference[T, V, C]) GetRootNode() *yaml.Node {
if r == nil {
return nil
}
obj := r.GetObject()
if obj == nil {
return nil
}
// Try to get the root node from the object via GetRootNode method
type nodeWithRootNode interface {
GetRootNode() *yaml.Node
}
if nodeWithRoot, ok := any(obj).(nodeWithRootNode); ok {
return nodeWithRoot.GetRootNode()
}
return nil
}
// GetParent returns the immediate parent reference if this reference was resolved via a reference chain.
//
// Returns nil if:
// - This reference was not resolved via a reference (accessed directly)
// - This reference is the top-level reference in a chain
// - The reference was accessed by iterating through document components rather than reference resolution
//
// Example: main.yaml -> external.yaml#/Parameter -> Parameter object
// The intermediate external.yaml reference's GetParent() returns the original main.yaml reference.
func (r *Reference[T, V, C]) GetParent() *Reference[T, V, C] {
if r == nil {
return nil
}
return r.parent
}
// GetTopLevelParent returns the top-level parent reference if this reference was resolved via a reference chain.
//
// Returns nil if:
// - This reference was not resolved via a reference (accessed directly)
// - This reference is already the top-level reference
// - The reference was accessed by iterating through document components rather than reference resolution
//
// Example: main.yaml -> external.yaml#/Param -> chained.yaml#/Param -> final Parameter object
// The intermediate references' GetTopLevelParent() returns the original main.yaml reference.
func (r *Reference[T, V, C]) GetTopLevelParent() *Reference[T, V, C] {
if r == nil {
return nil
}
return r.topLevelParent
}
// SetParent sets the immediate parent reference for this reference.
// This is a public API for manually constructing reference chains.
//
// Use this when you need to manually establish parent-child relationships
// between references, typically when creating reference chains programmatically
// rather than through the normal resolution process.
func (r *Reference[T, V, C]) SetParent(parent *Reference[T, V, C]) {
if r == nil {
return
}
r.parent = parent
}
// SetTopLevelParent sets the top-level parent reference for this reference.
// This is a public API for manually constructing reference chains.
//
// Use this when you need to manually establish the root of a reference chain,
// typically when creating reference chains programmatically rather than
// through the normal resolution process.
func (r *Reference[T, V, C]) SetTopLevelParent(topLevelParent *Reference[T, V, C]) {
if r == nil {
return
}
r.topLevelParent = topLevelParent
}
// Validate will validate the reusable object against the Arazzo specification.
func (r *Reference[T, V, C]) Validate(ctx context.Context, opts ...validation.Option) []error {
if r == nil {
return []error{errors.New("reference is nil")}
}
core := r.GetCore()
if core == nil {
return []error{errors.New("reference core is nil")}
}
errs := []error{}
if core.Reference.Present {
if err := r.Reference.Validate(); err != nil {
errs = append(errs, validation.NewValueError(validation.SeverityError, validation.RuleValidationInvalidSyntax, fmt.Errorf("reference.$ref is invalid: %w", err), core, core.Reference))
}
} else if r.Object != nil {
// Use the validator interface V to validate the object
var validator V
if v, ok := any(r.Object).(V); ok {
validator = v
errs = append(errs, validator.Validate(ctx, opts...)...)
}
}
r.Valid = len(errs) == 0 && core.GetValid()
return errs
}
func (r *Reference[T, V, C]) Populate(source any) error {
var s *core.Reference[C]
switch src := source.(type) {
case *core.Reference[C]:
s = src
case core.Reference[C]:
s = &src
default:
return fmt.Errorf("expected *core.Reference[C] or core.Reference[C], got %T", source)
}
if s.Reference.Present {
r.Reference = pointer.From(references.Reference(*s.Reference.Value))
r.Summary = s.Summary.Value
r.Description = s.Description.Value
} else {
if err := marshaller.PopulateWithContext(s.Object, &r.Object, nil); err != nil {
return err
}
}
r.SetCore(s)
return nil
}
func (r *Reference[T, V, C]) GetNavigableNode() (any, error) {
if !r.IsReference() {
return r.Object, nil
}
obj := r.GetObject()
if obj == nil {
return nil, errors.New("unresolved reference")
}
return obj, nil
}
func (r *Reference[T, V, C]) GetReferenceResolutionInfo() *references.ResolveResult[Reference[T, V, C]] {
if r == nil {
return nil
}
if !r.IsReference() {
return nil
}
r.ensureMutex()
r.cacheMutex.RLock()
defer r.cacheMutex.RUnlock()
if r.referenceResolutionCache == nil {
return nil
}
return r.referenceResolutionCache
}
func (r *Reference[T, V, C]) resolve(ctx context.Context, opts references.ResolveOptions) (*T, *Reference[T, V, C], []error, error) {
if !r.IsReference() {
return r.Object, nil, nil, nil
}
r.ensureMutex()
// Check if already resolved (with read lock)
r.cacheMutex.RLock()
if r.referenceResolutionCache != nil {
cache := r.referenceResolutionCache
validationErrs := r.validationErrsCache
r.cacheMutex.RUnlock()
if cache.Object.IsReference() {
return nil, cache.Object, validationErrs, nil
} else {
return cache.Object.Object, nil, validationErrs, nil
}
}
r.cacheMutex.RUnlock()
// Need to resolve (with write lock)
r.cacheMutex.Lock()
defer r.cacheMutex.Unlock()
// Double-check after acquiring write lock
if r.referenceResolutionCache != nil {
if r.referenceResolutionCache.Object.IsReference() {
return nil, r.referenceResolutionCache.Object, r.validationErrsCache, nil
} else {
return r.referenceResolutionCache.Object.Object, nil, r.validationErrsCache, nil
}
}
rootDoc, ok := opts.RootDocument.(*OpenAPI)
if !ok {
return nil, nil, nil, fmt.Errorf("root document must be *OpenAPI, got %T", opts.RootDocument)
}
// Use $self as base URI if present in the target document (OpenAPI 3.2+)
// The $self field provides the self-assigned URI of the document per RFC3986 Section 5.1.1
resolveOpts := opts
if targetDoc, ok := opts.TargetDocument.(*OpenAPI); ok && targetDoc != nil {
if self := targetDoc.GetSelf(); self != "" {
resolveOpts.TargetLocation = self
}
}
result, validationErrs, err := references.Resolve(ctx, *r.Reference, unmarshaler[T, V, C](rootDoc), resolveOpts)
if err != nil {
return nil, nil, validationErrs, err
}
r.referenceResolutionCache = result
r.validationErrsCache = validationErrs
if r.referenceResolutionCache.Object.IsReference() {
return nil, r.referenceResolutionCache.Object, r.validationErrsCache, nil
} else {
return r.referenceResolutionCache.Object.Object, nil, r.validationErrsCache, nil
}
}
// resolveObjectWithTracking recursively resolves references while tracking visited references to detect cycles
func resolveObjectWithTracking[T any, V interfaces.Validator[T], C marshaller.CoreModeler](ctx context.Context, ref *Reference[T, V, C], opts references.ResolveOptions, referenceChain []string) ([]error, error) {
// If this is not a reference, return the inline object
if !ref.IsReference() {
return nil, nil
}
// Get the absolute reference string for tracking using the extracted logic
reference := ref.GetReference()
absRefResult, err := references.ResolveAbsoluteReference(reference, opts.TargetLocation)
if err != nil {
return nil, err
}
jsonPtr := string(reference.GetJSONPointer())
absRef := utils.BuildAbsoluteReference(absRefResult.AbsoluteReference, jsonPtr)
// Check for circular reference by looking for the current reference in the chain
for _, chainRef := range referenceChain {
if chainRef == absRef {
// Build circular reference error message showing the full chain
chainWithCurrent := referenceChain
chainWithCurrent = append(chainWithCurrent, absRef)
ref.ensureMutex()
ref.cacheMutex.Lock()
ref.circularErrorFound = true
ref.cacheMutex.Unlock()
return nil, fmt.Errorf("circular reference detected: %s", joinReferenceChain(chainWithCurrent))
}
}
// Add this reference to the chain
newChain := referenceChain
newChain = append(newChain, absRef)
// Resolve the current reference
obj, nextRef, validationErrs, err := ref.resolve(ctx, opts)
if err != nil {
return validationErrs, err
}
// If we have an object already resolved then finish here
if obj != nil {
return validationErrs, nil
}
// If we got another reference, recursively resolve it with the resolved document as the new target
if nextRef != nil {
// Set parent links for the resolved reference
// The resolved reference's parent is the current reference
// The top-level parent is either the current reference's top-level parent, or the current reference if it's the top-level
var topLevel *Reference[T, V, C]
if ref.topLevelParent != nil {
topLevel = ref.topLevelParent
} else {
topLevel = ref
}
nextRef.SetParent(ref)
nextRef.SetTopLevelParent(topLevel)
// For chained resolutions, we need to use the resolved document from the previous step
// The ResolveResult.ResolvedDocument should be used as the new TargetDocument
ref.ensureMutex()
ref.cacheMutex.RLock()
targetDoc := ref.referenceResolutionCache.ResolvedDocument
targetLoc := ref.referenceResolutionCache.AbsoluteDocumentPath
ref.cacheMutex.RUnlock()
opts.TargetDocument = targetDoc
opts.TargetLocation = targetLoc
return resolveObjectWithTracking(ctx, nextRef, opts, newChain)
}
return validationErrs, fmt.Errorf("unable to resolve reference: %s", ref.GetReference())
}
// joinReferenceChain joins the reference chain with arrows to show the circular path
func joinReferenceChain(chain []string) string {
if len(chain) == 0 {
return ""
}
if len(chain) == 1 {
return chain[0]
}
var result strings.Builder
result.WriteString(chain[0])
for i := 1; i < len(chain); i++ {
result.WriteString(" -> ")
result.WriteString(chain[i])
}
return result.String()
}
func unmarshaler[T any, V interfaces.Validator[T], C marshaller.CoreModeler](_ *OpenAPI) func(context.Context, *yaml.Node, bool) (*Reference[T, V, C], []error, error) {
return func(ctx context.Context, node *yaml.Node, skipValidation bool) (*Reference[T, V, C], []error, error) {
var ref Reference[T, V, C]
validationErrs, err := marshaller.UnmarshalNode(ctx, "reference", node, &ref)
if skipValidation {
validationErrs = nil
}
if err != nil {
return nil, validationErrs, err
}
return &ref, validationErrs, nil
}
}
// referenceInitGlobalMutex serializes initialization of per-Reference mutexes
// to avoid data races on r.initMutex when ensureMutex is called concurrently.
var referenceInitGlobalMutex sync.Mutex
// ensureMutex initializes the mutex if it's nil (lazy initialization).
// Uses sync.Once (pointer) to guarantee thread-safe single initialization
// while keeping Reference safe to copy before first use.
func (r *Reference[T, V, C]) ensureMutex() {
// Guard lazy initialization of r.initMutex with a global mutex to avoid
// concurrent read/write races on the pointer field.
referenceInitGlobalMutex.Lock()
if r.initMutex == nil {
r.initMutex = &sync.Once{}
}
initOnce := r.initMutex
referenceInitGlobalMutex.Unlock()
initOnce.Do(func() {
r.cacheMutex = &sync.RWMutex{}
})
}