Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions go/internal/osvutil/schema/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"regexp"
"strings"
"sync"
"unicode/utf8"

"github.com/ossf/osv-schema/bindings/go/osvconstants"
Expand All @@ -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 {
Expand Down Expand Up @@ -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)
}
Expand Down
21 changes: 21 additions & 0 deletions go/internal/osvutil/schema/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package schema

import (
"strings"
"sync"
"testing"

"k8s.io/apimachinery/pkg/util/yaml"
Expand Down Expand Up @@ -185,3 +186,23 @@ func TestHasValidPrefix(t *testing.T) {
t.Errorf("HasValidPrefix mismatched prefix = true, want false")
}
}

func TestValidate_Concurrent(t *testing.T) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a little weird in that it doesn't really test that the schema is only being compiled once, but whatever

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just remove the test probably.

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()
}
Loading