Files
schemas/internal/validation/validate.go

197 lines
6.5 KiB
Go
Raw Normal View History

package validation
import (
"encoding/json"
"fmt"
"io/fs"
"regexp"
"sort"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
const schemaBase = "https://schemas.maximumdirect.net/"
type Record struct {
Name string `json:"name"`
Version string `json:"version"`
Contract string `json:"contract"`
ID string `json:"id"`
Path string `json:"path"`
}
type Catalog struct {
FormatVersion int `json:"format_version"`
Schemas []Record `json:"schemas"`
}
type Set struct {
Catalog Catalog
schemas map[string]*Schema
selections map[string]string
}
type Schema struct {
Record Record
compiled *jsonschema.Schema
}
var schemaVersion = regexp.MustCompile(`^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$`)
func Load(root fs.FS) (*Set, error) {
data, err := fs.ReadFile(root, "catalog.json")
if err != nil {
return nil, fmt.Errorf("catalog.json: %w", err)
}
// Decode through the shared profile as well, so duplicate JSON keys fail.
if !json.Valid(data) {
return nil, fmt.Errorf("catalog.json: expected JSON syntax")
}
if _, err := Decode(data); err != nil {
return nil, fmt.Errorf("catalog.json: %w", err)
}
set := &Set{schemas: make(map[string]*Schema), selections: make(map[string]string)}
if err := json.Unmarshal(data, &set.Catalog); err != nil {
return nil, fmt.Errorf("catalog.json: %w", err)
}
if set.Catalog.FormatVersion != 1 {
return nil, fmt.Errorf("catalog.json: unsupported format_version %d", set.Catalog.FormatVersion)
}
compiler := jsonschema.NewCompiler()
compiler.DefaultDraft(jsonschema.Draft2020)
compiler.UseLoader(offlineLoader{})
paths := make(map[string]bool)
for i, record := range set.Catalog.Schemas {
label := fmt.Sprintf("catalog.json schemas[%d] (%s@%s)", i, record.Name, record.Version)
if !fs.ValidPath(record.Name) || !schemaVersion.MatchString(record.Version) {
return nil, fmt.Errorf("%s: invalid schema name or SemVer", label)
}
// Numeric prerelease identifiers have no leading zero under SemVer.
pre, _, _ := strings.Cut(record.Version, "+")
if _, pre, ok := strings.Cut(pre, "-"); ok {
for _, part := range strings.Split(pre, ".") {
if len(part) > 1 && part[0] == '0' && strings.Trim(part, "0123456789") == "" {
return nil, fmt.Errorf("%s: invalid numeric prerelease identifier", label)
}
}
}
expected := record.Name + "/v" + record.Version + "/schema.json"
contractPrefix := "maximumdirect." + strings.ReplaceAll(record.Name, "/", ".") + ".v"
generation := strings.TrimPrefix(record.Contract, contractPrefix)
if record.Path != expected || record.ID != schemaBase+expected ||
!strings.HasPrefix(record.Contract, contractPrefix) ||
generation == "" || generation[0] == '0' || strings.Trim(generation, "0123456789") != "" {
return nil, fmt.Errorf("%s: path, ID, or contract does not match the schema identity", label)
}
key := record.Name + "@" + record.Version
if _, ok := set.selections[key]; ok {
return nil, fmt.Errorf("%s: duplicate name/version", label)
}
if _, ok := set.schemas[record.ID]; ok {
return nil, fmt.Errorf("%s: duplicate ID", label)
}
if paths[record.Path] {
return nil, fmt.Errorf("%s: duplicate path", label)
}
data, err := fs.ReadFile(root, record.Path)
if err != nil {
return nil, fmt.Errorf("%s: %w", record.Path, err)
}
if !json.Valid(data) {
return nil, fmt.Errorf("%s: expected JSON syntax", record.Path)
}
value, err := Decode(data)
if err != nil {
return nil, fmt.Errorf("%s: %w", record.Path, err)
}
doc, ok := value.(map[string]any)
if !ok {
return nil, fmt.Errorf("%s: expected a schema object", record.Path)
}
properties, _ := doc["properties"].(map[string]any)
marker, _ := properties["schema_version"].(map[string]any)
if doc["$schema"] != "https://json-schema.org/draft/2020-12/schema" || doc["$id"] != record.ID || marker["const"] != record.Contract {
return nil, fmt.Errorf("%s: schema dialect, ID, or contract disagrees with inventory", record.Path)
}
if err := compiler.AddResource(record.ID, value); err != nil {
return nil, fmt.Errorf("%s: %w", record.Path, err)
}
paths[record.Path] = true
set.selections[key] = record.ID
set.schemas[record.ID] = &Schema{Record: record}
}
// Only version roots at the canonical schema paths are active contracts.
err = fs.WalkDir(root, ".", func(file string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() && (entry.Name() == ".git" || file == "dist" || file == "docs" || file == "tests") {
return fs.SkipDir
}
if entry.IsDir() || !strings.HasSuffix(file, "/schema.json") {
return nil
}
parts := strings.Split(file, "/")
if len(parts) < 3 || !strings.HasPrefix(parts[len(parts)-2], "v") {
return nil
}
if !paths[file] {
return fmt.Errorf("%s: versioned schema is absent from catalog.json", file)
}
return nil
})
if err != nil {
return nil, err
}
for _, record := range set.Catalog.Schemas {
compiled, err := compiler.Compile(record.ID)
if err != nil {
return nil, fmt.Errorf("compile %s: %w", record.Path, err)
}
set.schemas[record.ID].compiled = compiled
}
return set, nil
}
type offlineLoader struct{}
func (offlineLoader) Load(url string) (any, error) {
return nil, fmt.Errorf("schema resource %q is absent from the local distribution; network loading is disabled", url)
}
func (s *Set) Select(selection string) (*Schema, error) {
id, ok := s.selections[selection]
if !ok {
return nil, fmt.Errorf("unknown exact schema selection %q; use name@version from catalog.json", selection)
}
return s.schemas[id], nil
}
func (s *Schema) Validate(value any) error {
if err := s.compiled.Validate(value); err != nil {
return fmt.Errorf("structure: %w", err)
}
if s.Record.Name == "glossary" {
return uniqueGlossaryIDs(value.(map[string]any)["collections"].(map[string]any))
}
return nil
}
func uniqueGlossaryIDs(collections map[string]any) error {
names := make([]string, 0, len(collections))
for name := range collections {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
entries := collections[name].(map[string]any)["entries"].([]any)
seen := make(map[string]int, len(entries))
for i, entry := range entries {
id := entry.(map[string]any)["id"].(string)
if previous, exists := seen[id]; exists {
return fmt.Errorf("semantic: /collections/%s/entries/%d/id: duplicate ID %q (first at entry %d)", escape(name), i, id, previous)
}
seen[id] = i
}
}
return nil
}