Load independently versioned schemas from an offline catalog

This commit is contained in:
2026-11-29 04:30:44 +00:00
parent d4488ab454
commit 2bf4e82e3d
4 changed files with 256 additions and 44 deletions

8
catalog.json Normal file
View File

@@ -0,0 +1,8 @@
{
"format_version": 1,
"schemas": [
{"name": "glossary", "version": "0.1.0", "contract": "maximumdirect.glossary.v1", "id": "https://schemas.maximumdirect.net/glossary/v0.1.0/schema.json", "path": "glossary/v0.1.0/schema.json"},
{"name": "rpg/party", "version": "0.1.0", "contract": "maximumdirect.rpg.party.v1", "id": "https://schemas.maximumdirect.net/rpg/party/v0.1.0/schema.json", "path": "rpg/party/v0.1.0/schema.json"},
{"name": "rpg/campaign", "version": "0.1.0", "contract": "maximumdirect.rpg.campaign.v1", "id": "https://schemas.maximumdirect.net/rpg/campaign/v0.1.0/schema.json", "path": "rpg/campaign/v0.1.0/schema.json"}
]
}

25
docs/catalog.md Normal file
View File

@@ -0,0 +1,25 @@
# Schema inventory
Root `catalog.json` uses `format_version: 1` and a `schemas` array with one record
per independent schema version. Each record has:
| Field | Meaning |
| --- | --- |
| `name` | Schema name, including its domain namespace, such as `rpg/party`. |
| `version` | Full SemVer, such as `0.1.0`. |
| `contract` | Document generation, such as `maximumdirect.rpg.party.v1`. |
| `id` | Canonical absolute schema identity under `https://schemas.maximumdirect.net/`. |
| `path` | Repository-relative `<name>/v<version>/schema.json`. |
The ID equals the canonical domain plus the path. `semantics.md` and `examples/`
are adjacent to each schema. Multiple versions may share a document generation;
select exactly `name@version` rather than inferring a definition from the marker.
The inventory includes every active versioned schema root and all retained
published versions. Names/versions, IDs, and paths are unique. Historical origin
snapshots and negative fixtures remain outside that inventory. Loading registers
all inventoried resources before compilation and resolves references offline.
A catalog on `main` includes development candidates. The catalog in an immutable
published CalVer tag identifies released versions. Its records do not carry the
distribution version or imply publication by their presence.

View File

@@ -0,0 +1,101 @@
package validation
import (
"encoding/json"
"io/fs"
"os"
"strings"
"testing"
"testing/fstest"
)
func TestCatalogSelection(t *testing.T) {
root := os.DirFS("../..")
data, err := fs.ReadFile(root, "catalog.json")
if err != nil {
t.Fatal(err)
}
var catalog Catalog
if err := json.Unmarshal(data, &catalog); err != nil {
t.Fatal(err)
}
files := fstest.MapFS{}
for _, record := range catalog.Schemas {
content, err := fs.ReadFile(root, record.Path)
if err != nil {
t.Fatal(err)
}
files[record.Path] = &fstest.MapFile{Data: content}
}
record := catalog.Schemas[0]
next := record
next.Version = "0.2.0"
next.Path = "glossary/v0.2.0/schema.json"
next.ID = schemaBase + next.Path
var schema map[string]any
if err := json.Unmarshal(files[record.Path].Data, &schema); err != nil {
t.Fatal(err)
}
schema["$id"] = next.ID
schema["required"] = []string{"schema_version", "collections", "synthetic_test_field"}
content, err := json.Marshal(schema)
if err != nil {
t.Fatal(err)
}
files[next.Path] = &fstest.MapFile{Data: content}
catalog.Schemas = append(catalog.Schemas, next)
setCatalog := func() {
t.Helper()
data, err := json.Marshal(catalog)
if err != nil {
t.Fatal(err)
}
files["catalog.json"] = &fstest.MapFile{Data: data}
}
setCatalog()
set, err := Load(files)
if err != nil {
t.Fatal(err)
}
old, err := set.Select("glossary@0.1.0")
if err != nil {
t.Fatal(err)
}
newer, err := set.Select("glossary@0.2.0")
if err != nil {
t.Fatal(err)
}
value := map[string]any{"schema_version": "maximumdirect.glossary.v1", "collections": map[string]any{}}
if err := old.Validate(value); err != nil {
t.Fatal(err)
}
if err := newer.Validate(value); err == nil {
t.Fatal("selection did not distinguish definitions sharing a marker")
}
if _, err := set.Select("glossary"); err == nil {
t.Fatal("implicit latest selection accepted")
}
for _, change := range []func(){
func() { catalog.Schemas = append(catalog.Schemas, record) },
func() { catalog.Schemas[0].ID += "/wrong" },
func() { catalog.Schemas[0].Path = "other/schema.json" },
func() { catalog.Schemas[0].Contract = "maximumdirect.rpg.party.v1" },
func() { catalog.Schemas = catalog.Schemas[1:] },
func() { delete(files, record.Path) },
} {
original := append([]Record(nil), catalog.Schemas...)
originalFile := files[record.Path]
change()
setCatalog()
if _, err := Load(files); err == nil {
t.Fatal("invalid inventory accepted")
}
catalog.Schemas = original
files[record.Path] = originalFile
}
setCatalog()
files[record.Path] = &fstest.MapFile{Data: []byte(strings.Replace(string(files[record.Path].Data), `"$ref": "#/$defs/text"`, `"$ref": "https://example.invalid/missing.json"`, 1))}
if _, err := Load(files); err == nil || !strings.Contains(err.Error(), "network loading is disabled") {
t.Fatalf("missing reference did not fail locally: %v", err)
}
}

View File

@@ -4,65 +4,149 @@ import (
"encoding/json"
"fmt"
"io/fs"
"regexp"
"sort"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
const schemaBase = "https://forge.maximumdirect.net/eric/schemas/raw/tag/"
const schemaBase = "https://schemas.maximumdirect.net/"
var contractNames = []string{"campaign", "glossary", "party"}
// Set is a compiled, offline schema set loaded from an unpacked distribution.
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 {
schemas map[string]*jsonschema.Schema
Catalog Catalog
schemas map[string]*Schema
selections map[string]string
}
type Schema struct {
Record Record
compiled *jsonschema.Schema
}
// Load compiles every contract, including meta-schema validation, using only
// locally registered resources and the library's built-in dialect definitions.
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) {
version, err := fs.ReadFile(root, "VERSION")
data, err := fs.ReadFile(root, "catalog.json")
if err != nil {
return nil, fmt.Errorf("read VERSION: %w", err)
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{})
ids := make(map[string]string)
for _, name := range contractNames {
file := "schemas/" + name + ".schema.json"
data, err := fs.ReadFile(root, file)
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", file, err)
return nil, fmt.Errorf("%s: %w", record.Path, err)
}
if !json.Valid(data) {
return nil, fmt.Errorf("%s: expected JSON syntax", file)
return nil, fmt.Errorf("%s: expected JSON syntax", record.Path)
}
value, err := Decode(data)
if err != nil {
return nil, fmt.Errorf("%s: %w", file, err)
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", file)
return nil, fmt.Errorf("%s: expected a schema object", record.Path)
}
id := schemaBase + strings.TrimSpace(string(version)) + "/" + file
if doc["$schema"] != "https://json-schema.org/draft/2020-12/schema" || doc["$id"] != id {
return nil, fmt.Errorf("%s: expected Draft 2020-12 and $id %q", file, id)
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(id, value); err != nil {
return nil, fmt.Errorf("%s: %w", file, err)
if err := compiler.AddResource(record.ID, value); err != nil {
return nil, fmt.Errorf("%s: %w", record.Path, err)
}
ids[name] = id
paths[record.Path] = true
set.selections[key] = record.ID
set.schemas[record.ID] = &Schema{Record: record}
}
set := &Set{schemas: make(map[string]*jsonschema.Schema)}
for _, name := range contractNames {
schema, err := compiler.Compile(ids[name])
// 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 nil, fmt.Errorf("compile %s: %w", name, err)
return err
}
set.schemas["maximumdirect."+name+".v1"] = schema
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
}
@@ -73,26 +157,20 @@ 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)
}
// Validate checks structure, then the selected semantic rules. It does not
// resolve imports or references, populate defaults, or mutate the input.
func (s *Set) Validate(value any) error {
doc, ok := value.(map[string]any)
func (s *Set) Select(selection string) (*Schema, error) {
id, ok := s.selections[selection]
if !ok {
return fmt.Errorf("structure: /: expected a document object")
return nil, fmt.Errorf("unknown exact schema selection %q; use name@version from catalog.json", selection)
}
version, ok := doc["schema_version"].(string)
if !ok {
return fmt.Errorf("structure: /schema_version: expected a contract identifier string")
}
schema := s.schemas[version]
if schema == nil {
return fmt.Errorf("structure: /schema_version: unsupported contract %q", version)
}
if err := schema.Validate(value); err != nil {
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 version == "maximumdirect.glossary.v1" {
return uniqueGlossaryIDs(doc["collections"].(map[string]any))
if s.Record.Name == "glossary" {
return uniqueGlossaryIDs(value.(map[string]any)["collections"].(map[string]any))
}
return nil
}