Skip to content
Open
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
6 changes: 4 additions & 2 deletions datamodel/low/base/schema_build.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,11 @@ func (s *Schema) Build(ctx context.Context, root *yaml.Node, idx *index.SpecInde
if utils.IsNodeArray(typeValue) {
refs := make([]low.ValueReference[string], 0, len(typeValue.Content))
for r := range typeValue.Content {
// An alias keeps the anchor name as its value, so read the node it points to.
item := utils.NodeAlias(typeValue.Content[r])
refs = append(refs, low.ValueReference[string]{
Value: typeValue.Content[r].Value,
ValueNode: typeValue.Content[r],
Value: item.Value,
ValueNode: item,
})
}
s.Type = low.NodeReference[SchemaDynamicValue[string, []low.ValueReference[string]]]{
Expand Down
20 changes: 20 additions & 0 deletions datamodel/low/base/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,26 @@ const: tasty`
assert.Equal(t, "tasty", schConst)
}

func TestSchema_Build_TypeListWithAlias(t *testing.T) {
build := func(spec string) *Schema {
var rootNode yaml.Node
assert.NoError(t, yaml.Unmarshal([]byte(spec), &rootNode))
sch := Schema{}
assert.NoError(t, low.BuildModel(rootNode.Content[0].Content[3], &sch))
assert.NoError(t, sch.Build(context.Background(), rootNode.Content[0].Content[3], nil))
return &sch
}
// An alias in a list of types reads the value it points to, not the name of its anchor.
aliased := build("name: &object string\nschema: {type: [*object, 'null']}")
plain := build("name: string\nschema: {type: [string, 'null']}")
assert.True(t, aliased.Type.Value.IsB())
if assert.Len(t, aliased.Type.Value.B, 2) {
assert.Equal(t, "string", aliased.Type.Value.B[0].Value)
assert.Equal(t, "null", aliased.Type.Value.B[1].Value)
}
assert.Equal(t, plain.Hash(), aliased.Hash())
}

func TestSchema_Build_PropsLookup(t *testing.T) {
yml := `components:
schemas:
Expand Down
241 changes: 226 additions & 15 deletions what-changed/model/schema_usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ package model
import (
"context"
"iter"
"slices"
"strconv"
"strings"
"sync"

Expand Down Expand Up @@ -106,6 +108,18 @@ type usageWalker struct {
visited [schemaObject + 1]schemaUsage
targets map[string]*yaml.Node
unknown bool
// nullable adds null to the types of a schema. Only OpenAPI 3.0 defines it, so it is kept when the version is unknown.
nullable bool
// siblings applies the keywords next to $ref as well. OpenAPI 3.1 does, and the schema model only reads them that
// way with TransformSiblingRefs, so without both only the referenced schema counts.
siblings bool
// dropped counts the keywords being walked that the model drops next to a $ref.
dropped int
// throughDropped is set once the walk reaches a schema through keywords the model drops next to a $ref, or through
// a $ref the model does not resolve, and madeExclusive once it keeps the direction of the branches of a oneOf.
throughDropped, madeExclusive bool
// sharedUnions shares the branches of every oneOf, as before.
sharedUnions bool
}

func buildSchemaUsage(idx *index.SpecIndex) schemaUsage {
Expand All @@ -116,21 +130,38 @@ func buildSchemaUsage(idx *index.SpecIndex) schemaUsage {
if root.Kind == yaml.DocumentNode && len(root.Content) > 0 {
root = root.Content[0]
}
w := usageWalker{index: idx, targets: make(map[string]*yaml.Node)}
for i := range w.visited {
w.visited[i] = make(schemaUsage)
}
for key, value := range usageFields(root) {
switch key {
case v3.JSONSchemaDialectLabel:
if !knownUsageDialect(value) {
return nil
version, known := idx.ResolveDocumentVersion()
walk := func(sharedUnions bool) *usageWalker {
w := &usageWalker{
index: idx,
targets: make(map[string]*yaml.Node),
nullable: !known || version < 3.1,
siblings: known && version >= 3.1 && idx.GetConfig() != nil && idx.GetConfig().TransformSiblingRefs,
sharedUnions: sharedUnions,
}
for i := range w.visited {
w.visited[i] = make(schemaUsage)
}
for key, value := range usageFields(root) {
switch key {
case v3.JSONSchemaDialectLabel:
if !knownUsageDialect(value) {
w.unknown = true
return w
}
case v3.PathsLabel:
w.openAPIEntries(value, pathItemObject, 0)
case v3.WebhooksLabel:
w.each(value, pathItemObject, sharedSchema)
}
case v3.PathsLabel:
w.openAPIEntries(value, pathItemObject, 0)
case v3.WebhooksLabel:
w.each(value, pathItemObject, sharedSchema)
}
return w
}
w := walk(false)
// The walk follows the keywords the model drops next to a $ref, as it did before. That did not matter while every
// oneOf was shared, so the document is walked again that way when both happen.
if !w.unknown && w.madeExclusive && w.throughDropped {
w = walk(true)
}
if w.unknown {
return nil
Expand Down Expand Up @@ -176,10 +207,19 @@ func (w *usageWalker) each(node *yaml.Node, object usageObject, dir schemaDirect
}

func (w *usageWalker) walk(node *yaml.Node, object usageObject, dir schemaDirection) {
w.walkReached(node, object, dir, false)
}

// walkReached walks node, which referenced tells is reached through a reference rather than written in place.
func (w *usageWalker) walkReached(node *yaml.Node, object usageObject, dir schemaDirection, referenced bool) {
aliased := node != nil && node.Kind == yaml.AliasNode
node = utils.NodeAlias(node)
if w.unknown || node == nil || node.Kind != yaml.MappingNode {
return
}
if object == schemaObject && w.dropped > 0 {
w.throughDropped = true
}
visited := w.visited[object]
if prior, seen := visited[node]; seen && prior&dir == dir {
return
Expand All @@ -200,16 +240,28 @@ func (w *usageWalker) walk(node *yaml.Node, object usageObject, dir schemaDirect
}
}
}
// The schema model drops the keywords next to a $ref without TransformSiblingRefs, when it reaches the schema through
// a $ref, and for an alias in a list. Next to the $ref of anything other than a schema, such as a response or a path
// item, it always drops them. The walk still follows them, as before, and records that it did. In OpenAPI 3.0 the
// model still reads them where the schema is written, so treating them as dropped there only shares more unions.
dropped := (object != schemaObject || !w.siblings || referenced || aliased) && usageField(node, v3.RefLabel) != nil
for key, value := range usageFields(node) {
if key == v3.RefLabel {
ref := utils.NodeAlias(value).Value
// The model does not resolve a $ref whose value is an alias, so the walk reaches what the model does not.
if value.Kind == yaml.AliasNode {
w.throughDropped = true
}
if target := w.localTarget(ref); target != nil {
w.walk(target, object, sameInstance)
w.walkReached(target, object, sameInstance, true)
continue
}
w.unknown = true
return
}
if dropped {
w.dropped++
}
switch object {
case pathItemObject, operationObject:
w.operationField(key, value, dir)
Expand All @@ -229,6 +281,9 @@ func (w *usageWalker) walk(node *yaml.Node, object usageObject, dir schemaDirect
case schemaObject:
w.schemaField(key, value, dir, sameInstance)
}
if dropped {
w.dropped--
}
}
}

Expand Down Expand Up @@ -264,7 +319,17 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc
case v3.NotLabel, v3.IfLabel, v3.ContainsLabel:
w.walk(value, schemaObject, sharedSchema)
case v3.OneOfLabel:
w.each(value, schemaObject, sharedSchema)
// A oneOf rejects an instance that matches more than one branch, so changing one branch can change what the
// union accepts in the opposite direction: widening a branch can make an instance match a second one, and
// narrowing it can leave an instance that matched two branches with only one. Branches that no instance can
// match at the same time cannot interfere with each other, so they keep the direction, as with anyOf.
// A shared direction is the same either way, so the branches are only checked when it is not.
if !w.sharedUnions && sameInstance != sharedSchema && w.exclusiveBranches(value) {
w.madeExclusive = true
w.each(value, schemaObject, sameInstance)
} else {
w.each(value, schemaObject, sharedSchema)
}
case v3.SchemaDialectLabel:
if !knownUsageDialect(value) {
w.unknown = true
Expand All @@ -275,6 +340,152 @@ func (w *usageWalker) schemaField(key string, value *yaml.Node, dir, sameInstanc
}
}

// exclusiveBranches reports whether no instance can match two of the branches, so that exclusivity does not depend
// on what a branch contains. That holds for a single branch and for branches that accept different types.
func (w *usageWalker) exclusiveBranches(branches *yaml.Node) bool {
branches = utils.NodeAlias(branches)
if branches.Kind != yaml.SequenceNode {
return false
}
if len(branches.Content) == 1 {
return true
}
seen := make(map[string]bool)
for _, branch := range branches.Content {
types, ok := w.instanceTypes(branch)
if !ok {
return false
}
for t := range types {
if seen[t] {
return false
}
seen[t] = true
}
}
return true
}

// jsonTypes are the instance types of JSON Schema. A type name outside this list cannot be compared with another one.
var jsonTypes = map[string]bool{
"null": true, "boolean": true, "object": true, "array": true, "number": true, "string": true, "integer": true,
}

// instanceTypes returns an upper bound of the JSON types a schema accepts. OpenAPI 3.0 ignores the siblings of $ref, so
// only the referenced schema counts there. In 3.1 they apply as well, so a type next to a reference narrows the bound.
// That only holds for the schema itself, written in place: the schema model reads a schema it reaches through a $ref
// as the target of its own $ref, without the type next to it, and does the same with an alias in a list.
// It reports false when it cannot tell: no type along the references, a type that cannot be read, a reference that
// cannot be resolved, a cycle of references, or types along the references that have nothing in common, which is more
// likely a mistake than a schema that accepts nothing. The same goes for the boolean schema false.
func (w *usageWalker) instanceTypes(node *yaml.Node) (map[string]bool, bool) {
var bound map[string]bool
followed := make([]*yaml.Node, 0, 8)
aliased := node != nil && node.Kind == yaml.AliasNode
for {
node = utils.NodeAlias(node)
// The boolean schema true accepts every instance, like {}, so it narrows nothing.
if utils.IsNodeBoolValue(node) {
if accepts, _ := strconv.ParseBool(node.Value); accepts {
return bound, len(bound) > 0
}
}
if node.Kind != yaml.MappingNode || slices.Contains(followed, node) {
return nil, false
}
followed = append(followed, node)
var declared *yaml.Node
ref := ""
nullable := false
for key, value := range usageFields(node) {
switch key {
case v3.TypeLabel:
declared = utils.NodeAlias(value)
case v3.RefLabel:
// The model does not resolve a $ref whose value is an alias.
if value.Kind == yaml.AliasNode {
return nil, false
}
ref = utils.NodeAlias(value).Value
case v3.NullableLabel:
// Read it as the schema model does: a YAML boolean, in any spelling that YAML accepts.
if utils.IsNodeBoolValue(value) {
nullable, _ = strconv.ParseBool(utils.NodeAlias(value).Value)
}
}
}
if declared != nil && (ref == "" || (w.siblings && len(followed) == 1 && !aliased)) {
types, ok := w.declaredTypes(declared, nullable)
if !ok {
return nil, false
}
bound = intersectTypes(bound, types)
}
if ref == "" {
return bound, len(bound) > 0
}
if node = w.localTarget(ref); node == nil {
return nil, false
}
}
}

// declaredTypes returns the JSON types of a type declaration, or false when it cannot be read.
func (w *usageWalker) declaredTypes(declared *yaml.Node, nullable bool) (map[string]bool, bool) {
var names []string
switch {
// The schema model only reads a single type from a YAML string, so `type: null` declares no type at all.
case utils.IsNodeStringValue(declared):
names = []string{declared.Value}
case declared.Kind == yaml.SequenceNode:
for _, item := range declared.Content {
names = append(names, utils.NodeAlias(item).Value)
}
}
if len(names) == 0 {
return nil, false
}
// OpenAPI 3.0 adds null with nullable. In 3.1 nullable means nothing.
if nullable && w.nullable {
names = append(names, "null")
}
types := make(map[string]bool)
for _, name := range names {
if !jsonTypes[name] {
return nil, false
}
types[name] = true
// Every integer is a number, so the two overlap.
if name == "number" {
types["integer"] = true
}
}
return types, true
}

// intersectTypes narrows bound to the types it shares with types. A nil bound does not restrict anything yet.
func intersectTypes(bound, types map[string]bool) map[string]bool {
if bound == nil {
return types
}
for t := range bound {
if !types[t] {
delete(bound, t)
}
}
return bound
}

// usageField returns the value of one field of a mapping, or nil when the mapping does not have it.
func usageField(node *yaml.Node, name string) *yaml.Node {
for key, value := range usageFields(node) {
if key == name {
return value
}
}
return nil
}

// Other dialects may introduce applicators that the OpenAPI schema walk cannot follow.
func knownUsageDialect(value *yaml.Node) bool {
switch strings.TrimSuffix(utils.NodeAlias(value).Value, "#") {
Expand Down
Loading
Loading