diff --git a/go/internal/osvutil/schema/schema.go b/go/internal/osvutil/schema/schema.go index ef6570fd4d1..0dff47864d7 100644 --- a/go/internal/osvutil/schema/schema.go +++ b/go/internal/osvutil/schema/schema.go @@ -9,6 +9,7 @@ import ( "fmt" "regexp" "strings" + "sync" "unicode/utf8" "github.com/ossf/osv-schema/bindings/go/osvconstants" @@ -23,6 +24,10 @@ var schemaBytes []byte var validEcosystems = populateValidEcosystems() +var compiledSchema = sync.OnceValues(func() (*gojsonschema.Schema, error) { + return gojsonschema.NewSchema(gojsonschema.NewBytesLoader(schemaBytes)) +}) + func populateValidEcosystems() map[osvconstants.Ecosystem]struct{} { var s struct { Defs struct { @@ -84,10 +89,12 @@ func HasValidPrefix(name string, idPrefixes []string) bool { // Validate checks the given data against the OSV JSON schema. func Validate(data []byte) error { - schemaLoader := gojsonschema.NewBytesLoader(schemaBytes) - documentLoader := gojsonschema.NewBytesLoader(data) + compiled, err := compiledSchema() + if err != nil { + return fmt.Errorf("failed to run schema validation: %w", err) + } - result, err := gojsonschema.Validate(schemaLoader, documentLoader) + result, err := compiled.Validate(gojsonschema.NewBytesLoader(data)) if err != nil { return fmt.Errorf("failed to run schema validation: %w", err) } diff --git a/go/internal/osvutil/schema/schema_test.go b/go/internal/osvutil/schema/schema_test.go index eb7ad4191cc..6da1994beda 100644 --- a/go/internal/osvutil/schema/schema_test.go +++ b/go/internal/osvutil/schema/schema_test.go @@ -16,6 +16,7 @@ package schema import ( "strings" + "sync" "testing" "k8s.io/apimachinery/pkg/util/yaml" @@ -185,3 +186,23 @@ func TestHasValidPrefix(t *testing.T) { t.Errorf("HasValidPrefix mismatched prefix = true, want false") } } + +func TestValidate_Concurrent(t *testing.T) { + valid := []byte(`{"id":"OSV-2026-1","modified":"2026-01-01T00:00:00Z"}`) + invalid := []byte(`{"id":"OSV-2026-1"}`) + + var wg sync.WaitGroup + for range 8 { + wg.Go(func() { + for range 10 { + if err := Validate(valid); err != nil { + t.Errorf("Validate(valid) unexpected error: %v", err) + } + if err := Validate(invalid); err == nil || !strings.HasPrefix(err.Error(), "schema validation failed:\n") { + t.Errorf("Validate(invalid) = %v, want schema validation failure", err) + } + } + }) + } + wg.Wait() +}