Files
narratio/internal/glossary/glossary.go

160 lines
4.3 KiB
Go

// Package glossary owns the shared native glossary representation and validation.
package glossary
import (
"bytes"
_ "embed"
"encoding/json"
"fmt"
"sort"
"sync"
"github.com/santhosh-tekuri/jsonschema/v6"
)
// Collection preserves an explicitly supplied empty instruction.
type Collection struct {
Instruction *string `yaml:"instruction,omitempty" json:"instruction,omitempty"`
Entries []Entry `yaml:"entries" json:"entries"`
}
// Entry retains native fields and any additional vocabulary metadata.
type Entry struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name" json:"name"`
Category string `yaml:"category" json:"category"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Aliases []string `yaml:"aliases,omitempty" json:"aliases,omitempty"`
Plural *string `yaml:"plural,omitempty" json:"plural,omitempty"`
Extra map[string]any `yaml:",inline" json:"-"`
}
// MarshalJSON retains extension fields when validating or serializing typed entries.
func (entry Entry) MarshalJSON() ([]byte, error) {
type fields Entry
b, err := json.Marshal(fields(entry))
if err != nil {
return nil, err
}
var result map[string]any
if err := json.Unmarshal(b, &result); err != nil {
return nil, err
}
for key, value := range entry.Extra {
if _, known := result[key]; !known {
result[key] = value
}
}
return json.Marshal(result)
}
// CatalogRevision identifies the upstream source of the embedded schema.
const CatalogRevision = "a1a87edafd59a1de545a1c0b4efe5feeb80348e0"
//go:embed glossary-v1.schema.json
var schemaData []byte
const schemaURL = "https://forge.maximumdirect.net/eric/narratio-reference-catalog/schemas/glossary-v1.schema.json"
var compiled struct {
sync.Once
document, partial *jsonschema.Schema
err error
}
type offlineLoader struct{}
func (offlineLoader) Load(url string) (any, error) {
return nil, fmt.Errorf("schema resource unavailable: %s", url)
}
func schemas() (*jsonschema.Schema, *jsonschema.Schema, error) {
compiled.Do(func() {
var doc any
if compiled.err = json.Unmarshal(schemaData, &doc); compiled.err != nil {
return
}
c := jsonschema.NewCompiler()
c.UseLoader(offlineLoader{})
if compiled.err = c.AddResource(schemaURL, doc); compiled.err != nil {
return
}
if compiled.document, compiled.err = c.Compile(schemaURL); compiled.err != nil {
return
}
compiled.partial, compiled.err = c.Compile(schemaURL + "#/$defs/partialCollection")
})
return compiled.document, compiled.partial, compiled.err
}
// ValidatePartial validates a decoded collection contribution without requiring entries.
func ValidatePartial(value any) error {
_, schema, err := schemas()
if err != nil {
return fmt.Errorf("compile glossary schema: %w", err)
}
v, err := jsonValue(value)
if err != nil {
return err
}
if err := schema.Validate(v); err != nil {
return fmt.Errorf("glossary contribution: %w", err)
}
return nil
}
// ValidateDocument validates decoded complete named collections and their IDs.
func ValidateDocument(value any) error {
schema, _, err := schemas()
if err != nil {
return fmt.Errorf("compile glossary schema: %w", err)
}
v, err := jsonValue(value)
if err != nil {
return err
}
if err := schema.Validate(v); err != nil {
return fmt.Errorf("glossary document: %w", err)
}
doc := v.(map[string]any)
names := make([]string, 0, len(doc))
for name := range doc {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
if err := uniqueIDs("collection "+name, doc[name]); err != nil {
return err
}
}
return nil
}
func jsonValue(value any) (any, error) {
data, err := json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("encode glossary data: %w", err)
}
decoder := json.NewDecoder(bytes.NewReader(data))
decoder.UseNumber()
var result any
if err := decoder.Decode(&result); err != nil {
return nil, fmt.Errorf("decode glossary data: %w", err)
}
return result, nil
}
func uniqueIDs(context string, value any) error {
collection := value.(map[string]any)
entries, _ := collection["entries"].([]any)
seen := make(map[string]bool, len(entries))
for _, raw := range entries {
id := raw.(map[string]any)["id"].(string)
if seen[id] {
return fmt.Errorf("%s: duplicate entry id %q", context, id)
}
seen[id] = true
}
return nil
}