Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
360 changes: 142 additions & 218 deletions bundler/bundler.go

Large diffs are not rendered by default.

156 changes: 28 additions & 128 deletions bundler/bundler_composer.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@ package bundler

import (
"context"
"fmt"
"net/url"
"path/filepath"
"strings"
"sync"

"github.com/pb33f/go-yaml"
v3 "github.com/pb33f/libopenapi/datamodel/high/v3"
Expand Down Expand Up @@ -39,104 +37,19 @@ type discriminatorMappingWithContext struct {
node *yaml.Node // The YAML node containing the mapping value
sourceIdx *index.SpecIndex // The index where the mapping was found
canonicalKey string // ref.FullDefinition captured before bundling mutates refs
target *processRef
targetIdx *index.SpecIndex // The index where the resolved ref actually lives (may differ from sourceIdx)
}

type handleIndexConfig struct {
idx *index.SpecIndex
type compositionContext struct {
rootIdx *index.SpecIndex
model *v3.Document
indexes []*index.SpecIndex
refMap *orderedmap.Map[string, *processRef]
seen sync.Map
inlineRequired []*processRef
compositionConfig *BundleCompositionConfig
discriminatorMappings []*discriminatorMappingWithContext // mapping nodes with source context
origins ComponentOriginMap // component origins for navigation
}

// handleIndex will recursively explore the indexes and their references, building a map of references
// to be processed later. It will also check for circular references and avoid infinite loops.
// everything is stored in the handleIndexConfig, which is passed around to avoid passing too many parameters.
func handleIndex(c *handleIndexConfig) error {
mappedReferences := c.idx.GetMappedReferences()
sequencedReferences := c.idx.GetRawReferencesSequenced()
var indexesToExplore []*index.SpecIndex

for _, sequenced := range sequencedReferences {
if sequenced.IsExtensionRef {
continue
}
mappedReference := mappedReferences[sequenced.FullDefinition]
if mappedReference == nil {
mappedReference, _ = c.idx.SearchIndexForReference(sequenced.FullDefinition)
}

// Check for invalid sibling properties if strict validation is enabled
if c.compositionConfig.StrictValidation &&
c.idx.GetConfig().SpecInfo.VersionNumeric == 3.0 &&
sequenced.HasSiblingProperties {
siblingKeys := make([]string, 0, len(sequenced.SiblingProperties))
for key := range sequenced.SiblingProperties {
siblingKeys = append(siblingKeys, key)
}
return fmt.Errorf("invalid OpenAPI 3.0 specification: $ref cannot have sibling properties. Found $ref '%s' with siblings %v at line %d, column %d",
sequenced.FullDefinition, siblingKeys, sequenced.Node.Line, sequenced.Node.Column)
}

// if we're in the root document, don't bundle anything.
refExp := strings.Split(sequenced.FullDefinition, "#/")
var foundIndex *index.SpecIndex

// make sure to use the correct index.
// https://github.com/pb33f/libopenapi/issues/397
for _, i := range c.indexes {
if i.GetSpecAbsolutePath() == refExp[0] {
foundIndex = i
if mappedReference != nil && !mappedReference.Circular {

lookup := sequenced.FullDefinition
mr := i.FindComponent(context.Background(), lookup)
if mr != nil {
// Use the component from the matching index.
mappedReference = mr
break
}
}
}
}
refMapKey := processRefMapKey(mappedReference, sequenced)
if foundIndex != nil && mappedReference != nil {
// Avoid recomposing components that resolve back to the root document.
if c.rootIdx != nil && foundIndex.GetSpecAbsolutePath() == c.rootIdx.GetSpecAbsolutePath() {
continue
}
// Store the reference to be composed in the root.
if kk := c.refMap.GetOrZero(refMapKey); kk == nil {
c.refMap.Set(refMapKey, &processRef{
idx: foundIndex,
ref: mappedReference,
seqRef: sequenced,
mapKey: refMapKey,
name: mappedReference.Name,
})
}
if _, ok := c.seen.Load(foundIndex.GetSpecAbsolutePath()); !ok {
c.seen.Store(foundIndex.GetSpecAbsolutePath(), mappedReference) // TODO: replace with map.
indexesToExplore = append(indexesToExplore, foundIndex)
}
}
}

for _, idx := range indexesToExplore {
c.idx = idx
if err := handleIndex(c); err != nil {
return err
}
}
return nil
}

// openAPIRootKeys contains known OpenAPI root-level keys that should NOT be
// recomposed as components. OpenAPI root keys are always lowercase per spec.
// Package-level to avoid allocation on each call.
Expand Down Expand Up @@ -177,7 +90,7 @@ func rootSupportsMediaTypeComponents(rootIdx *index.SpecIndex) bool {

// processReference will extract a reference from the current index, and transform it into a first class
// top-level component in the root OpenAPI document.
func processReference(model *v3.Document, pr *processRef, cf *handleIndexConfig) error {
func processReference(model *v3.Document, pr *processRef, cf *compositionContext) error {
idx := pr.idx
var components *v3.Components
var err error
Expand Down Expand Up @@ -222,8 +135,8 @@ func processReference(model *v3.Document, pr *processRef, cf *handleIndexConfig)
}
}

unknown := func(procRef *processRef, config *handleIndexConfig) {
if l := config.idx.GetLogger(); l != nil {
unknown := func(procRef *processRef, config *compositionContext) {
if l := config.rootIdx.GetLogger(); l != nil {
l.Warn("[bundler] unable to compose reference, not sure where it goes.", "$ref", procRef.ref.FullDefinition)
}
// no idea what do with this, so we will inline it.
Expand Down Expand Up @@ -354,11 +267,12 @@ func isOpenAPIComponentNameChar(r rune) bool {
// This handles cases where a schema is ONLY referenced via discriminator mapping.
func enqueueDiscriminatorMappingTargets(
mappings []*discriminatorMappingWithContext,
cf *handleIndexConfig,
cf *compositionContext,
rootIdx *index.SpecIndex,
) {
) []*processRef {
var targets []*processRef
for _, mapping := range mappings {
refValue := mapping.node.Value
refValue := utils.NodeAlias(mapping.node).Value

// Skip empty values
if refValue == "" {
Expand Down Expand Up @@ -389,6 +303,21 @@ func enqueueDiscriminatorMappingTargets(
continue
}

// Lookup may return the relative spelling from the source document. Qualify
// it with the resolved file before deduplicating across mapping sources.
if foundIdx != nil {
_, fragment, hasFragment := strings.Cut(ref.FullDefinition, "#/")
full := foundIdx.GetSpecAbsolutePath()
if hasFragment {
full += "#/" + fragment
}
if full != "" && full != ref.FullDefinition {
resolved := *ref
resolved.FullDefinition = full
ref = &resolved
}
}

// Cache the canonical key and target index before bundling mutates refs.
mapping.canonicalKey = ref.FullDefinition
mapping.targetIdx = foundIdx
Expand All @@ -397,7 +326,7 @@ func enqueueDiscriminatorMappingTargets(

// Skip targets already queued for composition.
if existing := cf.refMap.GetOrZero(mapKey); existing != nil {
existing.fromDiscriminator = true
mapping.target = existing
continue
}

Expand All @@ -415,8 +344,11 @@ func enqueueDiscriminatorMappingTargets(
name: name,
fromDiscriminator: true,
}
mapping.target = pr
cf.refMap.Set(mapKey, pr)
targets = append(targets, pr)
}
return targets
}

// resolveDiscriminatorMappingTarget attempts to resolve a mapping value as a whole-file reference.
Expand Down Expand Up @@ -484,38 +416,6 @@ func resolveDiscriminatorMappingTarget(
return ref, idx
}

// handleDiscriminatorMappingIndexes ensures indexes discovered only via discriminator mappings
// are explored so their internal refs are composed.
func handleDiscriminatorMappingIndexes(
cf *handleIndexConfig,
rootIdx *index.SpecIndex,
rolodex *index.Rolodex,
) error {
for _, mapping := range cf.discriminatorMappings {
if mapping.targetIdx == nil {
continue
}
if mapping.targetIdx == rootIdx {
continue
}
if _, ok := cf.seen.Load(mapping.targetIdx.GetSpecAbsolutePath()); ok {
continue
}

// Refresh indexes in case new ones were loaded during mapping resolution.
if rolodex != nil {
cf.indexes = rolodex.GetIndexes()
}

cf.idx = mapping.targetIdx
if err := handleIndex(cf); err != nil {
return err
}
}
cf.idx = rootIdx
return nil
}

func deriveNameFromFullDefinition(fullDef string) string {
if idx := strings.Index(fullDef, "#"); idx != -1 {
fullDef = fullDef[:idx]
Expand Down
28 changes: 6 additions & 22 deletions bundler/bundler_composer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func TestBundlerComposed(t *testing.T) {
// err = os.WriteFile("test/specs/bundled.yaml", bytes, 0644)

v3Doc.Model.Components = nil
err = processReference(&v3Doc.Model, &processRef{}, &handleIndexConfig{compositionConfig: &BundleCompositionConfig{}})
err = processReference(&v3Doc.Model, &processRef{}, &compositionContext{compositionConfig: &BundleCompositionConfig{}})
assert.Error(t, err)
}

Expand All @@ -67,8 +67,7 @@ func TestProcessReference_ContextualSingleSegmentRejectsUnsafeNode(t *testing.T)
Components: &v3.Components{},
}
idx := newVersionedIndex(3.1)
cf := &handleIndexConfig{
idx: idx,
cf := &compositionContext{
rootIdx: idx,
inlineRequired: nil,
compositionConfig: &BundleCompositionConfig{Delimiter: "__"},
Expand All @@ -95,8 +94,7 @@ func TestProcessReference_JSONSchemaDefsReturnsComposeError(t *testing.T) {
},
}
idx := newVersionedIndex(3.2)
cf := &handleIndexConfig{
idx: idx,
cf := &compositionContext{
rootIdx: idx,
compositionConfig: &BundleCompositionConfig{Delimiter: "__"},
}
Expand All @@ -118,8 +116,7 @@ func TestProcessReference_JSONSchemaDefsFallsBackWhenSchemasMissing(t *testing.T
Components: &v3.Components{},
}
idx := newVersionedIndex(3.2)
cf := &handleIndexConfig{
idx: idx,
cf := &compositionContext{
rootIdx: idx,
compositionConfig: &BundleCompositionConfig{Delimiter: "__"},
}
Expand Down Expand Up @@ -310,13 +307,13 @@ components:
ref.FullDefinition = ref.FullDefinition + "#/components/schemas/Cat"
}

cf := &handleIndexConfig{
cf := &compositionContext{
refMap: orderedmap.New[string, *processRef](),
}

enqueueDiscriminatorMappingTargets(mappings, cf, rolodex.GetRootIndex())

pr := cf.refMap.GetOrZero(ref.FullDefinition)
pr := cf.refMap.GetOrZero(filepath.Join(tmpDir, "schemas", "Cat.yaml") + "#/components/schemas/Cat")
require.NotNil(t, pr)
assert.Equal(t, "Cat", pr.name)
}
Expand Down Expand Up @@ -391,19 +388,6 @@ paths: {}`), &rootNode))
assert.NotEqual(t, yaml.DocumentNode, ref.Node.Kind)
}

func TestHandleDiscriminatorMappingIndexes_SkipsRootTarget(t *testing.T) {
rootIdx := &index.SpecIndex{}
cf := &handleIndexConfig{
idx: rootIdx,
rootIdx: rootIdx,
discriminatorMappings: []*discriminatorMappingWithContext{{targetIdx: rootIdx}},
}

err := handleDiscriminatorMappingIndexes(cf, rootIdx, nil)
require.NoError(t, err)
assert.Equal(t, rootIdx, cf.idx)
}

// TestBundleBytesComposed_DiscriminatorMapping tests that composed bundling correctly
// updates discriminator mappings when external schemas are moved to components.
func TestBundleBytesComposed_DiscriminatorMapping(t *testing.T) {
Expand Down
Loading
Loading