Repository navigation
fix(index): resolve plain-name $anchor fragments - #710
Tjmstudios wants to merge 2 commits into
Conversation
A $ref such as "#foo" never resolved: only $id was registered, so the index reported the component as missing and the document failed to build. That covers "#foo", "#bar" inside an $id resource and "https://example.com/r#bar". Register $anchor during extraction, keyed by the enclosing $id or the document path, with the same validity, example-payload and first-wins rules as $id. The rolodex aggregates the anchors like it does $id. ResolveRefViaSchemaId tries a plain-name fragment as an anchor first. The same "#foo" text names different schemas in different resources, so extracted refs and the search cache key it by resource rather than by the raw value. The resolver resolves "#foo" against the parent's document, so an anchor ref inside an external file finds that file's anchor. Cross-file "other.yaml#foo" is not covered; the rolodex still opens files by splitting on "#/".
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #710 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 315 317 +2
Lines 39758 39902 +144
==========================================
+ Hits 39758 39902 +144
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
| // registerSchemaAnchorAt records an $anchor under the base URI of the schema resource | ||
| // that declares it: the nearest $id, or the document itself. | ||
| func (index *SpecIndex) registerSchemaAnchorAt(node *yaml.Node, keyIndex int, seenPath []string, baseUri string) { | ||
| if underOpenAPIExamplePath(seenPath) || len(node.Content) <= keyIndex+1 { |
There was a problem hiding this comment.
[P2] Register anchors only at schema locations. A default payload containing {$anchor: selected, type: integer} claimed the name before a string schema declared $anchor: selected. BuildV3Model() succeeded, and a property referencing #selected acquired type integer. Please restrict registration to schema nodes and cover a default payload that precedes the real declaration.
There was a problem hiding this comment.
Fixed in b56d5f8. Anchors under default, const, enum, example(s), Link parameters/requestBody and x- extensions (including x- on Responses) are skipped now. Inside an $id resource the path is checked from the resource root. A property/component/response actually named default or x-foo still registers.
Added TestDocument_BuildV3Model_SchemaAnchorAfterDefaultPayload with your example. #selected resolves to the string schema now, it was integer before.
|
|
||
| definitionPath := "#" | ||
| if len(seenPath) > 0 { | ||
| definitionPath = "#/" + strings.Join(seenPath, "/") |
There was a problem hiding this comment.
[P2] Include the array index in the target pointer. I put distinct anchors on two adjacent prefixItems entries and referenced both. Each resolved to its own node, but both reported #/components/schemas/Tuple/prefixItems, so GetMappedReferences() retained only one target. Please carry the sequence index into the pointer and check that the mapped targets end in /0 and /1.
There was a problem hiding this comment.
Fixed in b56d5f8. The existing walk builds the full pointer now, indices included and ~// escaped. TestDocument_BuildV3Model_SchemaAnchorRefs checks GetMappedReferences() has both .../Tuple/prefixItems/0 and .../prefixItems/1, and TestBundleBytesComposed_AnchorRefsIntoPrefixItems covers bundling. Note SchemaIdEntry.DefinitionPath has indices now too.
| if baseUri == "" { | ||
| baseUri = index.specAbsolutePath | ||
| } | ||
| key := baseUri + fragment |
There was a problem hiding this comment.
[P2] Decode the URI fragment before anchor lookup. With $anchor: name, BuildV3Model() reports a missing component for $ref: '#na%6De'. The registry stores #name, but this lookup uses the encoded spelling. Please decode the fragment once, preserve the resource URI, and cover the encoded spelling in a document-build test.
There was a problem hiding this comment.
Fixed in b56d5f8. schemaAnchorFragmentName decodes the fragment once with url.PathUnescape. Lookup is base URI + #name, ref text is left as written. #%2Ffoo still counts as a JSON pointer. TestDocument_BuildV3Model_SchemaAnchorRefs builds #f%6Fo, #b%61r and https://example.com/r#b%61r.
An $anchor inside a default, enum, const or example payload, a Link's parameters or requestBody, or a specification extension registered as a declaration, so a payload earlier in the document took the name from the schema declared after it. Skip an $anchor whose path runs through data, judged from the root of its enclosing $id resource, or from the document root outside any $id. $id keeps its existing rule. The definition path of an $anchor or $id came from the walk's own path, which has no sequence indices and drops some keys, so a ref into prefixItems pointed at the array. Build the JSON pointer during the extract-refs walk instead, with every key and index, writing "~" as "~0" and "/" as "~1". Decode a fragment once with url.PathUnescape before matching the anchor name, so "#f%6Fo" names foo and "#%2Ffoo" stays a JSON pointer. An "$anchor" or "$id" entry in a sequence such as required is no longer read as a key.
|
Thanks! All three are fixed in b56d5f8, tests are linked in each thread. Also in that commit:
Not handled here, can do a follow-up if you want:
This overlaps a bit with #708, which does the same thing for |
Summary
A
$refto a plain-name fragment such as#foofails to resolve, so the document doesn't build. This registers$anchorvalues and resolves those fragments against them.Problem
2020-12 defines
#nameas the schema with$anchor: namein the same resource. A resource is the nearest$id, or the document. Only$idwas registered, so#name,#barinside an$idresource, andhttps://example.com/r#barall fail.Changes
handleExtractRefsKeyregisters$anchornext to$id. The entry is keyed by<base URI>#<name>, where the base is the enclosing$idor the document path. Names that don't match^[A-Za-z_][-A-Za-z0-9._]*$and anchors in example payloads are skipped. When a name is declared twice, the first one wins, same as$id.$id(RegisterIdsFromIndex).ResolveRefViaSchemaIdlooks up a plain-name fragment as an anchor before trying$id. This coversFindComponent,SearchIndexForReferenceand extraction. The resolved ref is named after the schema it lands on (Name), as a pointer ref is.extractReferenceAtkeys a#nameref by its resource (<base URI>#name). The same text in two$idresources names two schemas, so keying by the raw value dropped the second ref and let a document anchor shadow a scoped one.SearchIndexForReferenceByReferenceWithContextcaches#nameunder the resource it was resolved in, for the same reason.buildRelativeLookupDefinitionsresolves#nameagainst the parent's document, so#nameinsidepet.yamlfindspet.yaml's anchor and not one in the root.Not covered: a cross-file
other.yaml#name. The rolodex splits on#/to open files, so the fragment stays attached to the file name. Fixing that is a separate change.libopenapi-validator still fails an anchor referenced from inside its
$idresource withduplicate anchor:RenderInlinecopies the$anchorinto the inlined copy.$idalready fails the same way onmain(duplicate id).Tests
index/schema_anchor_test.goandTestDocument_BuildV3Model_SchemaAnchorRefsindocument_test.go. All fail onmain, except the subtests that check what must not resolve (an anchor outside its resource, an invalid name, an example payload, an undeclared name) andTestRegisterSchemaAnchorAt_Skips.Releasetests inindex/index_model_test.goandindex/rolodex_test.goalso check that the new registries are cleared.go test ./...passes.