package testwire import ( "encoding/json" "os" "path/filepath" "strings" "sync" "github.com/google/jsonschema-go/jsonschema" "go.yaml.in/yaml/v3" ) // Contract validates values against the schemas of docs/openapi.yaml. The // end-to-end suite checks live daemon responses with it, and the // openapi_encodings contract checks the daemon's encoders with it directly. type Contract struct { Document map[string]any mu sync.Mutex schemas map[string]*jsonschema.Resolved } // LoadContract reads docs/openapi.yaml under the repository root. func LoadContract(root string) (*Contract, error) { data, err := os.ReadFile(filepath.Join(root, "docs", "openapi.yaml")) if err != nil { return nil, err } var document map[string]any if err := yaml.Unmarshal(data, &document); err != nil { return nil, err } return &Contract{Document: document, schemas: make(map[string]*jsonschema.Resolved)}, nil } // Dereference follows a local `$ref`, or answers the value itself. func (contract *Contract) Dereference(value map[string]any) map[string]any { if reference, ok := value["$ref"].(string); ok { var current any = contract.Document for part := range strings.SplitSeq(strings.TrimPrefix(reference, "#/"), "/") { current = current.(map[string]any)[strings.ReplaceAll(strings.ReplaceAll(part, "~1", "/"), "~0", "~")] } return current.(map[string]any) } return value } func schemaReferences(value any) any { switch value := value.(type) { case map[string]any: result := make(map[string]any, len(value)) for key, child := range value { if key == "$ref" { result[key] = strings.Replace(child.(string), "#/components/schemas/", "#/$defs/", 1) } else { result[key] = schemaReferences(child) } } return result case []any: result := make([]any, len(value)) for index, child := range value { result[index] = schemaReferences(child) } return result default: return value } } // Validate checks value, decoded from JSON, against schema, which may refer // to any component schema. func (contract *Contract) Validate(schema map[string]any, value any) error { encoded, err := json.Marshal(schema) if err != nil { return err } key := string(encoded) contract.mu.Lock() resolved := contract.schemas[key] if resolved == nil { root := schemaReferences(schema).(map[string]any) root["$defs"] = schemaReferences(contract.Document["components"].(map[string]any)["schemas"]) root["$schema"] = "https://json-schema.org/draft/2020-12/schema" encoded, err = json.Marshal(root) var parsed jsonschema.Schema if err == nil { err = json.Unmarshal(encoded, &parsed) } if err == nil { resolved, err = parsed.Resolve(nil) } if err == nil { contract.schemas[key] = resolved } } contract.mu.Unlock() if err != nil { return err } return resolved.Validate(value) } // ValidateComponent checks value against the component schema `name`. func (contract *Contract) ValidateComponent(name string, value any) error { return contract.Validate(map[string]any{"$ref": "#/components/schemas/" + name}, value) }