Cache compiled JSON schemas per validator

This commit is contained in:
2026-08-09 01:38:42 +00:00
parent d36d4e7689
commit 5d086c13ca
2 changed files with 172 additions and 19 deletions

View File

@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"fmt"
"sync"
"github.com/santhosh-tekuri/jsonschema/v6"
@@ -16,39 +17,50 @@ const ReasonCodeInvalidJSON = "invalid_json"
const ReasonCodeSchemaInvalid = "json_schema_invalid"
type Options struct{}
type Validator struct{}
type schemaIdentity struct {
id string
name string
version string
digest string
}
type compiledSchema struct {
schema *jsonschema.Schema
err error
}
type schemaCompiler func([]byte) (*jsonschema.Schema, error)
type Validator struct {
mu sync.Mutex
schemas map[schemaIdentity]compiledSchema
compile schemaCompiler
}
var _ contracts.SerializedValidator = (*Validator)(nil)
func New(Options) *Validator { return &Validator{} }
func New(Options) *Validator {
return &Validator{schemas: make(map[schemaIdentity]compiledSchema), compile: compileSchema}
}
func (v *Validator) Name() string { return Key }
func (v *Validator) ExecutionClass() contracts.ExecutionClass {
return contracts.ExecutionClassDeterministic
}
func (v *Validator) Validate(_ context.Context, req contracts.SerializedValidationRequest) (contracts.ValidationResult, error) {
return validate(req.Content, req.Schema.JSONSchema)
}
func validate(content, schemaContent []byte) (contracts.ValidationResult, error) {
if len(schemaContent) == 0 {
return contracts.ValidationResult{}, fmt.Errorf("response schema content is not available")
if len(req.Schema.JSONSchema) == 0 {
_, err := v.compiledSchema(req.Schema)
return contracts.ValidationResult{}, err
}
instance, err := jsonschema.UnmarshalJSON(bytes.NewReader(content))
instance, err := jsonschema.UnmarshalJSON(bytes.NewReader(req.Content))
if err != nil {
return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCodeInvalidJSON, Message: "payload is not valid JSON"}, nil
}
schemaDocument, err := jsonschema.UnmarshalJSON(bytes.NewReader(schemaContent))
schema, err := v.compiledSchema(req.Schema)
if err != nil {
return contracts.ValidationResult{}, fmt.Errorf("parse response schema: %w", err)
}
compiler := jsonschema.NewCompiler()
if err := compiler.AddResource("schema.json", schemaDocument); err != nil {
return contracts.ValidationResult{}, fmt.Errorf("load response schema: %w", err)
}
schema, err := compiler.Compile("schema.json")
if err != nil {
return contracts.ValidationResult{}, fmt.Errorf("compile response schema: %w", err)
return contracts.ValidationResult{}, err
}
if err := schema.Validate(instance); err != nil {
return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCodeSchemaInvalid, Message: "payload does not conform to response schema"}, nil
@@ -56,6 +68,49 @@ func validate(content, schemaContent []byte) (contracts.ValidationResult, error)
return contracts.ValidationResult{Approved: true}, nil
}
func (v *Validator) compiledSchema(schema contracts.ArtifactSchema) (*jsonschema.Schema, error) {
identity := schemaIdentity{
id: schema.ID,
name: schema.Name,
version: schema.Version,
digest: contracts.DigestArtifactSchema(schema),
}
v.mu.Lock()
defer v.mu.Unlock()
if v.schemas == nil {
v.schemas = make(map[schemaIdentity]compiledSchema)
}
if cached, ok := v.schemas[identity]; ok {
return cached.schema, cached.err
}
compiler := v.compile
if compiler == nil {
compiler = compileSchema
}
compiled, err := compiler(schema.JSONSchema)
v.schemas[identity] = compiledSchema{schema: compiled, err: err}
return compiled, err
}
func compileSchema(schemaContent []byte) (*jsonschema.Schema, error) {
if len(schemaContent) == 0 {
return nil, fmt.Errorf("response schema content is not available")
}
schemaDocument, err := jsonschema.UnmarshalJSON(bytes.NewReader(schemaContent))
if err != nil {
return nil, fmt.Errorf("parse response schema: %w", err)
}
compiler := jsonschema.NewCompiler()
if err := compiler.AddResource("schema.json", schemaDocument); err != nil {
return nil, fmt.Errorf("load response schema: %w", err)
}
schema, err := compiler.Compile("schema.json")
if err != nil {
return nil, fmt.Errorf("compile response schema: %w", err)
}
return schema, nil
}
func Spec() pipeline.ValidatorSpec {
return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
}