Use native ConfigKit loading for domain documents

This commit is contained in:
2026-11-29 16:31:19 +00:00
parent ac21977996
commit dbc2697090
6 changed files with 82 additions and 250 deletions

View File

@@ -52,7 +52,7 @@ func run(args []string, stdout, stderr io.Writer) int {
}
var value any
if err == nil {
value, err = validation.Decode(data)
value, err = validation.LoadDomain(file, data)
}
if err == nil {
err = schema.Validate(value)

7
go.mod
View File

@@ -4,7 +4,10 @@ go 1.27.0
require (
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3
go.yaml.in/yaml/v4 v4.0.0
go.maximumdirect.net/configkit v1.4.0
)
require golang.org/x/text v0.14.0 // indirect
require (
go.yaml.in/yaml/v4 v4.0.0 // indirect
golang.org/x/text v0.14.0 // indirect
)

2
go.sum
View File

@@ -2,6 +2,8 @@ github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxK
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 h1:1EYB5IzjZawrrnELUi78f9fPu57HuXjmddZPjrls/28=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
go.maximumdirect.net/configkit v1.4.0 h1:TfOupZbQ23/ZMs+xt5lmyukCF11ekqKep8KbmFQD63o=
go.maximumdirect.net/configkit v1.4.0/go.mod h1:ewu6blSokUDCMovy8JBXAdXRikGmlHXAQpFghnPWRfs=
go.yaml.in/yaml/v4 v4.0.0 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw=
go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=

View File

@@ -1,256 +1,17 @@
// Package validation supports this repository's contract checks. It is not a
// consumer SDK: consumers may use their own conforming YAML and schema tools.
// Package validation supports the repository's internal contract checks.
package validation
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math/big"
"strconv"
"strings"
"go.yaml.in/yaml/v4"
"go.maximumdirect.net/configkit"
)
// Decode uses the standard JSON decoder for JSON syntax and go-yaml otherwise,
// adapting both to the documented data model without losing number precision.
func Decode(data []byte) (any, error) {
if json.Valid(data) {
d := json.NewDecoder(bytes.NewReader(data))
d.UseNumber()
value, err := jsonValue(d, "")
if err != nil {
return nil, fmt.Errorf("decode: %w", err)
}
return value, nil
}
var document yaml.Node
if err := yaml.Load(data, &document, yaml.WithUniqueKeys()); err != nil {
return nil, fmt.Errorf("decode: %w", err)
}
d := decoder{active: make(map[*yaml.Node]bool), values: make(map[*yaml.Node]any)}
value, err := d.value(&document, "")
// LoadDomain acquires a completed domain mapping through the pinned native
// ConfigKit boundary. Schema and semantic validation consume its result directly.
func LoadDomain(label string, data []byte) (map[string]any, error) {
result, err := configkit.Load[map[string]any](configkit.Bytes(label, data))
if err != nil {
return nil, fmt.Errorf("decode: %w", err)
return nil, fmt.Errorf("load: %w", err)
}
return value, nil
}
// jsonValue consumes library-decoded tokens so duplicate keys, including keys
// with equivalent escape spellings, cannot be lost in a map unmarshalling step.
// Decode has already checked that the input is one syntactically valid value.
func jsonValue(d *json.Decoder, path string) (any, error) {
token, err := d.Token()
if err != nil {
return nil, err
}
switch token {
case json.Delim('{'):
value := make(map[string]any)
for d.More() {
token, err := d.Token()
if err != nil {
return nil, err
}
key := token.(string) // Valid JSON objects have string keys.
childPath := path + "/" + escape(key)
if _, exists := value[key]; exists {
return nil, fmt.Errorf("%s (byte %d): duplicate mapping key %q", pointer(childPath), d.InputOffset(), key)
}
value[key], err = jsonValue(d, childPath)
if err != nil {
return nil, err
}
}
_, err = d.Token() // Closing brace.
return value, err
case json.Delim('['):
value := make([]any, 0)
for d.More() {
child, err := jsonValue(d, fmt.Sprintf("%s/%d", path, len(value)))
if err != nil {
return nil, err
}
value = append(value, child)
}
_, err = d.Token() // Closing bracket.
return value, err
default:
return token, nil
}
}
type decoder struct {
active map[*yaml.Node]bool
values map[*yaml.Node]any
}
func (d *decoder) value(n *yaml.Node, path string) (any, error) {
if n == nil {
return nil, fmt.Errorf("%s: unresolved alias", pointer(path))
}
if d.active[n] {
return nil, nodeError(n, path, "cyclic alias")
}
if value, found := d.values[n]; found {
return value, nil
}
d.active[n] = true
defer delete(d.active, n)
var value any
var err error
switch n.Kind {
case yaml.DocumentNode:
if len(n.Content) != 1 {
return nil, nodeError(n, path, "expected one document")
}
value, err = d.value(n.Content[0], path)
case yaml.AliasNode:
value, err = d.value(n.Alias, path)
case yaml.MappingNode:
if n.ShortTag() != "!!map" {
return nil, nodeError(n, path, "unsupported mapping tag %q", n.Tag)
}
mapping := make(map[string]any, len(n.Content)/2)
for i := 0; i < len(n.Content); i += 2 {
keyValue, keyErr := d.value(n.Content[i], path)
if keyErr != nil {
return nil, keyErr
}
key, ok := keyValue.(string)
if !ok {
return nil, nodeError(n.Content[i], path, "mapping key must be a string")
}
childPath := path + "/" + escape(key)
if _, exists := mapping[key]; exists {
return nil, nodeError(n.Content[i], childPath, "duplicate mapping key %q", key)
}
mapping[key], err = d.value(n.Content[i+1], childPath)
if err != nil {
return nil, err
}
}
value = mapping
case yaml.SequenceNode:
if n.ShortTag() != "!!seq" {
return nil, nodeError(n, path, "unsupported sequence tag %q", n.Tag)
}
sequence := make([]any, len(n.Content))
for i, child := range n.Content {
sequence[i], err = d.value(child, fmt.Sprintf("%s/%d", path, i))
if err != nil {
return nil, err
}
}
value = sequence
case yaml.ScalarNode:
value, err = scalar(n)
if err != nil {
return nil, nodeError(n, path, "%v", err)
}
default:
return nil, nodeError(n, path, "expected a document value")
}
if err == nil {
d.values[n] = value
}
return value, err
}
func scalar(n *yaml.Node) (any, error) {
switch n.ShortTag() {
case "!!str":
// go-yaml resolves decimal numbers outside machine-float range as
// strings. Plain JSON numbers still retain numeric meaning in this
// profile, including when the source serialization is JSON.
if n.Style == 0 {
if number, ok := jsonNumber(n.Value); ok {
return number, nil
}
}
return n.Value, nil
case "!!timestamp":
// Date-like scalars are text in the shared data model, not time.Time.
return n.Value, nil
case "!!bool", "!!null":
var value any
err := n.Decode(&value)
return value, err
case "!!int":
text := strings.ReplaceAll(n.Value, "_", "")
integer, ok := new(big.Int).SetString(text, 0)
if !ok {
integer, ok = new(big.Int).SetString(text, 10)
}
if !ok {
return nil, fmt.Errorf("invalid integer %q", n.Value)
}
return json.Number(integer.String()), nil
case "!!float":
// Normalize YAML's leading '+', '.5', and '5.' spellings, retaining the
// decimal digits instead of converting through float64.
text := strings.TrimPrefix(strings.ReplaceAll(n.Value, "_", ""), "+")
// Check syntax before supplying missing zeroes. Range errors are allowed:
// the exact decimal representation need not fit in a machine float.
if _, err := strconv.ParseFloat(text, 64); err != nil && !errors.Is(err, strconv.ErrRange) {
return nil, fmt.Errorf("invalid float %q: %w", n.Value, err)
}
mantissa, exponent, hasExponent := strings.Cut(strings.ToLower(text), "e")
sign := ""
if strings.HasPrefix(mantissa, "-") {
sign, mantissa = "-", strings.TrimPrefix(mantissa, "-")
}
whole, fraction, hasPoint := strings.Cut(mantissa, ".")
whole = strings.TrimLeft(whole, "0")
if whole == "" {
whole = "0"
}
text = sign + whole
if hasPoint {
if fraction == "" {
fraction = "0"
}
text += "." + fraction
}
if hasExponent {
text += "e" + exponent
}
if number, ok := jsonNumber(text); ok {
return number, nil
}
return nil, fmt.Errorf("number %q is not a finite JSON number", n.Value)
default:
return nil, fmt.Errorf("tag %q has no shared JSON representation", n.Tag)
}
}
func jsonNumber(text string) (json.Number, bool) {
if !json.Valid([]byte(text)) {
return "", false
}
var value any
decoder := json.NewDecoder(strings.NewReader(text))
decoder.UseNumber()
if err := decoder.Decode(&value); err != nil {
return "", false
}
number, ok := value.(json.Number)
return number, ok
}
func nodeError(n *yaml.Node, path, format string, args ...any) error {
return fmt.Errorf("%s (line %d, column %d): %s", pointer(path), n.Line, n.Column, fmt.Sprintf(format, args...))
}
func pointer(path string) string {
if path == "" {
return "/"
}
return path
}
func escape(value string) string {
return strings.ReplaceAll(strings.ReplaceAll(value, "~", "~0"), "/", "~1")
return result.Config, nil
}

View File

@@ -0,0 +1,62 @@
package validation
import (
"reflect"
"strings"
"testing"
)
func TestNativeHandoff(t *testing.T) {
value, err := LoadDomain("synthetic.yml", []byte(`name: "Weather 🌧"
count: 9223372036854775807
amount: 0.123456789012345678901234567890
aliases: null
entries: []
context: {}
`))
if err != nil {
t.Fatal(err)
}
want := map[string]any{"name": "Weather 🌧", "count": int64(9223372036854775807), "amount": float64(0.12345678901234568), "aliases": nil, "entries": []any{}, "context": map[string]any{}}
if !reflect.DeepEqual(value, want) {
t.Fatalf("native result %#v differs from %#v", value, want)
}
}
func TestNativeFailures(t *testing.T) {
for _, input := range []string{
"a: 9223372036854775808", "a: 1e500", "a: yes", "a: TRUE", "a: 0x10",
"a: !!float 1", "a: &x value\nb: *x", "a: 1\na: 2", "1: value", `"<<": value`,
`{"name":"Weather \ud83c\udf27"}`, "config: {note: ordinary}",
} {
t.Run(input, func(t *testing.T) {
if _, err := LoadDomain("synthetic.yml", []byte(input)); err == nil || !strings.HasPrefix(err.Error(), "load:") {
t.Fatalf("want native failure, got %v", err)
}
})
}
}
func TestNativeControls(t *testing.T) {
value, err := LoadDomain("synthetic.yml", []byte(`records:
base: {name: Base}
child: {extends: base}
context:
extends: null
config: {note: ordinary}
`))
if err != nil {
t.Fatal(err)
}
records := value["records"].(map[string]any)
if !reflect.DeepEqual(records["base"], records["child"]) {
t.Fatalf("inheritance did not resolve: %#v", records)
}
context := value["context"].(map[string]any)
if _, found := context["extends"]; found {
t.Fatal("extends survived as ordinary data")
}
if !reflect.DeepEqual(context["config"], map[string]any{"note": "ordinary"}) {
t.Fatalf("nested config data changed: %#v", context)
}
}

View File

@@ -204,3 +204,7 @@ func uniqueGlossaryIDs(collections map[string]any) error {
}
return nil
}
func escape(value string) string {
return strings.ReplaceAll(strings.ReplaceAll(value, "~", "~0"), "/", "~1")
}