package validation import ( "bytes" "encoding/json" "fmt" "io/fs" "regexp" "sort" "strings" "github.com/santhosh-tekuri/jsonschema/v6" "golang.org/x/mod/semver" ) 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 current map[string]*Schema } 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) } if !json.Valid(data) { return nil, fmt.Errorf("catalog.json: expected JSON syntax") } set := &Set{schemas: make(map[string]*Schema), selections: make(map[string]string), current: make(map[string]*Schema)} 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) || !semver.IsValid("v"+record.Version) { return nil, fmt.Errorf("%s: invalid schema name or SemVer", 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 := decodeResource(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} previous := set.current[record.Name] if previous == nil || semver.Compare("v"+record.Version, "v"+previous.Record.Version) > 0 { set.current[record.Name] = set.schemas[record.ID] } } // 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 } // Schema resources are JSON, not operator configuration. Preserve exact numeric // constraints independently of the domain loader's numeric binding policy. func decodeResource(data []byte) (any, error) { if !json.Valid(data) { return nil, fmt.Errorf("expected one JSON value") } decoder := json.NewDecoder(bytes.NewReader(data)) decoder.UseNumber() var value any err := decoder.Decode(&value) return value, err } 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) { schema, ok := s.current[selection] if !ok { return nil, fmt.Errorf("unknown schema name %q; use a name from catalog.json", selection) } return schema, nil } // Current returns each name's highest local version in stable name order. func (s *Set) Current() []*Schema { names := make([]string, 0, len(s.current)) for name := range s.current { names = append(names, name) } sort.Strings(names) result := make([]*Schema, 0, len(names)) for _, name := range names { result = append(result, s.current[name]) } return result } 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 } func escape(value string) string { return strings.ReplaceAll(strings.ReplaceAll(value, "~", "~0"), "/", "~1") }