Files
go-sip/internal/contract/current.go
T

46 lines
1.2 KiB
Go

package contract
import (
"bytes"
"fmt"
"sync"
"git.ipao.vip/rogee/go-sip/contracts"
"github.com/santhosh-tekuri/jsonschema/v6"
)
var compiledSchemas sync.Map
// ValidateCurrent checks only the pinned shared HTTP/MQ contract.
// An absent schema is an error; it never falls back to historical bundles.
func ValidateCurrent(surface string, raw []byte) error {
var name string
switch surface {
case "config-read", "task-discovery", "mq":
name = surface + ".schema.json"
default:
return fmt.Errorf("invalid current contract surface %q", surface)
}
value, err := jsonschema.UnmarshalJSON(bytes.NewReader(raw))
if err != nil {
return &ValidationFailure{Surface: surface, Raw: append([]byte(nil), raw...), Reason: "invalid JSON encoding"}
}
key := "current/" + name
cached, ok := compiledSchemas.Load(key)
var schema *jsonschema.Schema
if ok {
schema = cached.(*jsonschema.Schema)
} else {
schema, err = contracts.CompileCurrent(name)
if err != nil {
return err
}
actual, _ := compiledSchemas.LoadOrStore(key, schema)
schema = actual.(*jsonschema.Schema)
}
if err := schema.Validate(value); err != nil {
return newValidationFailure(surface, raw, value, err)
}
return nil
}