Add typed spell validation strategies
This commit is contained in:
@@ -174,6 +174,30 @@ func TestMergeRejectsInvalidJSONAndNonJSONMediaTypes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTypedMergeUsesRequestOrderForReusableValueType(t *testing.T) {
|
||||
type notes struct{ Values []string }
|
||||
merger, err := NewTyped(func(values []notes) (notes, error) {
|
||||
var combined notes
|
||||
for _, value := range values {
|
||||
combined.Values = append(combined.Values, value.Values...)
|
||||
}
|
||||
return combined, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewTyped() error = %v", err)
|
||||
}
|
||||
result, err := merger.Merge(context.Background(), contracts.TypedMergeRequest[notes]{ExtractOutputs: []contracts.ExtractArtifact[notes]{
|
||||
{ChunkIndex: 4, Value: notes{Values: []string{"first"}}},
|
||||
{ChunkIndex: 1, Value: notes{Values: []string{"second"}}},
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("Merge() error = %v", err)
|
||||
}
|
||||
if got := result.Value.Values; !reflect.DeepEqual(got, []string{"first", "second"}) {
|
||||
t.Fatalf("Values = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func extractOutput(chunkID string, chunkIndex int, content string) contracts.ExtractOutput {
|
||||
return contracts.ExtractOutput{
|
||||
LaneID: "events",
|
||||
|
||||
62
internal/modules/generic/merge/appendorder/typed.go
Normal file
62
internal/modules/generic/merge/appendorder/typed.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package appendorder
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
)
|
||||
|
||||
// CombineFunc combines values in the source-chunk order supplied by the
|
||||
// framework. Implementations must not reorder the slice.
|
||||
type CombineFunc[T any] func([]T) (T, error)
|
||||
|
||||
type TypedMerger[T any] struct {
|
||||
combine CombineFunc[T]
|
||||
}
|
||||
|
||||
func NewTyped[T any](combine CombineFunc[T]) (*TypedMerger[T], error) {
|
||||
if combine == nil {
|
||||
return nil, mergerErrorf("combine function must not be nil")
|
||||
}
|
||||
return &TypedMerger[T]{combine: combine}, nil
|
||||
}
|
||||
|
||||
func (m *TypedMerger[T]) Key() string { return Key }
|
||||
|
||||
func (m *TypedMerger[T]) Merge(ctx context.Context, req contracts.TypedMergeRequest[T]) (contracts.TypedMergeResult[T], error) {
|
||||
if m == nil || m.combine == nil {
|
||||
return contracts.TypedMergeResult[T]{}, mergerErrorf("merger must not be nil")
|
||||
}
|
||||
if ctx == nil {
|
||||
return contracts.TypedMergeResult[T]{}, mergerErrorf("context must not be nil")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return contracts.TypedMergeResult[T]{}, mergerErrorf("context error before merge: %w", err)
|
||||
}
|
||||
values := make([]T, len(req.ExtractOutputs))
|
||||
for i, output := range req.ExtractOutputs {
|
||||
values[i] = output.Value
|
||||
}
|
||||
value, err := m.combine(values)
|
||||
if err != nil {
|
||||
return contracts.TypedMergeResult[T]{}, mergerErrorf("combine values: %w", err)
|
||||
}
|
||||
return contracts.TypedMergeResult[T]{Value: value}, nil
|
||||
}
|
||||
|
||||
func TypedModuleSpec(kind contracts.ArtifactKind) pipeline.ModuleSpec {
|
||||
spec := ModuleSpec()
|
||||
spec.ArtifactKind = kind
|
||||
return spec
|
||||
}
|
||||
|
||||
func RegisterTyped[T any](registry *pipeline.MergerRegistry, kind contracts.ArtifactKind, combine CombineFunc[T]) error {
|
||||
validateOptions := func(options map[string]any) error { return pipeline.RejectUnknownOptions(options) }
|
||||
return pipeline.RegisterMergerBuilder(registry, TypedModuleSpec(kind), validateOptions, func(request pipeline.BuildRequest) (contracts.Merger[T], error) {
|
||||
if err := pipeline.RejectUnknownOptions(request.Options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewTyped(combine)
|
||||
})
|
||||
}
|
||||
@@ -84,6 +84,19 @@ func TestNormalizeDefensivelyCopiesRawPayload(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTypedNormalizePassesThroughReusableValueType(t *testing.T) {
|
||||
type score struct{ Value int }
|
||||
result, err := NewTyped[score]().Normalize(context.Background(), contracts.TypedNormalizeRequest[score]{
|
||||
MergeOutput: contracts.MergeArtifact[score]{Value: score{Value: 7}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Normalize() error = %v", err)
|
||||
}
|
||||
if result.Value.Value != 7 {
|
||||
t.Fatalf("Value = %d, want 7", result.Value.Value)
|
||||
}
|
||||
}
|
||||
|
||||
func mergeOutput(content string) contracts.MergeOutput {
|
||||
return contracts.MergeOutput{
|
||||
LaneID: "events",
|
||||
|
||||
44
internal/modules/generic/normalize/noop/typed.go
Normal file
44
internal/modules/generic/normalize/noop/typed.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package noop
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
)
|
||||
|
||||
type TypedNormalizer[T any] struct{}
|
||||
|
||||
func NewTyped[T any]() *TypedNormalizer[T] { return &TypedNormalizer[T]{} }
|
||||
|
||||
func (n *TypedNormalizer[T]) Key() string { return Key }
|
||||
func (n *TypedNormalizer[T]) ReferenceSlots() []contracts.ReferenceSlot { return nil }
|
||||
|
||||
func (n *TypedNormalizer[T]) Normalize(ctx context.Context, req contracts.TypedNormalizeRequest[T]) (contracts.TypedNormalizeResult[T], error) {
|
||||
if n == nil {
|
||||
return contracts.TypedNormalizeResult[T]{}, normalizerErrorf("normalizer must not be nil")
|
||||
}
|
||||
if ctx == nil {
|
||||
return contracts.TypedNormalizeResult[T]{}, normalizerErrorf("context must not be nil")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return contracts.TypedNormalizeResult[T]{}, normalizerErrorf("context error before normalize: %w", err)
|
||||
}
|
||||
return contracts.TypedNormalizeResult[T]{Value: req.MergeOutput.Value}, nil
|
||||
}
|
||||
|
||||
func TypedModuleSpec(kind contracts.ArtifactKind) pipeline.ModuleSpec {
|
||||
spec := ModuleSpec()
|
||||
spec.ArtifactKind = kind
|
||||
return spec
|
||||
}
|
||||
|
||||
func RegisterTyped[T any](registry *pipeline.NormalizerRegistry, kind contracts.ArtifactKind) error {
|
||||
validateOptions := func(options map[string]any) error { return pipeline.RejectUnknownOptions(options) }
|
||||
return pipeline.RegisterNormalizerBuilder(registry, TypedModuleSpec(kind), validateOptions, func(request pipeline.BuildRequest) (contracts.Normalizer[T], error) {
|
||||
if err := pipeline.RejectUnknownOptions(request.Options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewTyped[T](), nil
|
||||
})
|
||||
}
|
||||
@@ -9,35 +9,76 @@ import (
|
||||
|
||||
const Key = "generic/always_accept"
|
||||
|
||||
var _ contracts.LegacyRawValidator = (*Validator)(nil)
|
||||
type Options struct{}
|
||||
type ChunkValidator struct{}
|
||||
type TypedValidator[T any] struct{}
|
||||
type legacyValidator struct{}
|
||||
|
||||
type Validator struct{}
|
||||
var _ contracts.ChunkValidator = (*ChunkValidator)(nil)
|
||||
|
||||
func New() *Validator {
|
||||
return &Validator{}
|
||||
}
|
||||
func NewChunk(Options) *ChunkValidator { return &ChunkValidator{} }
|
||||
func NewTyped[T any](Options) *TypedValidator[T] { return &TypedValidator[T]{} }
|
||||
|
||||
func (v *Validator) Name() string {
|
||||
return Key
|
||||
}
|
||||
|
||||
func (v *Validator) ExecutionClass() contracts.ExecutionClass {
|
||||
func (v *ChunkValidator) Name() string { return Key }
|
||||
func (v *ChunkValidator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
func (v *ChunkValidator) Validate(context.Context, contracts.ChunkValidationRequest) (contracts.ValidationResult, error) {
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
|
||||
func (v *Validator) Validate(ctx context.Context, req contracts.ValidationRequest) (contracts.ValidationResult, error) {
|
||||
func (v *TypedValidator[T]) Name() string { return Key }
|
||||
func (v *TypedValidator[T]) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
func (v *TypedValidator[T]) Validate(context.Context, contracts.TypedValidationRequest[T]) (contracts.ValidationResult, error) {
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
|
||||
func (v *legacyValidator) Name() string { return Key }
|
||||
func (v *legacyValidator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
func (v *legacyValidator) Validate(context.Context, contracts.ValidationRequest) (contracts.ValidationResult, error) {
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
|
||||
func Spec() pipeline.ValidatorSpec {
|
||||
return pipeline.ValidatorSpec{
|
||||
Key: Key,
|
||||
ExecutionClass: contracts.ExecutionClassDeterministic,
|
||||
}
|
||||
return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
|
||||
}
|
||||
|
||||
func Register(registry *pipeline.ValidatorRegistry) error {
|
||||
return registry.RegisterLegacyRawWithSpec(Spec(), func() (contracts.LegacyRawValidator, error) {
|
||||
return New(), nil
|
||||
if err := pipeline.RegisterChunkValidatorBuilder(registry, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.ChunkValidator, error) {
|
||||
options, err := DecodeOptions(request.Options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewChunk(options), nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return registry.RegisterLegacyRawBuilderWithSpec(Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.LegacyRawValidator, error) {
|
||||
if _, err := DecodeOptions(request.Options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &legacyValidator{}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func RegisterTyped[T any](registry *pipeline.ValidatorRegistry, kind contracts.ArtifactKind) error {
|
||||
return pipeline.RegisterTypedValidatorBuilder(registry, kind, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.TypedValidator[T], error) {
|
||||
options, err := DecodeOptions(request.Options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewTyped[T](options), nil
|
||||
})
|
||||
}
|
||||
|
||||
func DecodeOptions(options map[string]any) (Options, error) {
|
||||
if err := pipeline.RejectUnknownOptions(options); err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
return Options{}, nil
|
||||
}
|
||||
func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
)
|
||||
|
||||
func TestValidatorApproves(t *testing.T) {
|
||||
result, err := New().Validate(context.Background(), contracts.ValidationRequest{})
|
||||
result, err := NewChunk(Options{}).Validate(context.Background(), contracts.ChunkValidationRequest{})
|
||||
if err != nil {
|
||||
t.Fatalf("Validate() error = %v, want nil", err)
|
||||
}
|
||||
|
||||
@@ -10,39 +10,72 @@ import (
|
||||
const Key = "generic/always_reject"
|
||||
const ReasonCode = "always_reject"
|
||||
|
||||
var _ contracts.LegacyRawValidator = (*Validator)(nil)
|
||||
type Options struct{}
|
||||
type ChunkValidator struct{}
|
||||
type TypedValidator[T any] struct{}
|
||||
type legacyValidator struct{}
|
||||
|
||||
type Validator struct{}
|
||||
func NewChunk(Options) *ChunkValidator { return &ChunkValidator{} }
|
||||
func NewTyped[T any](Options) *TypedValidator[T] { return &TypedValidator[T]{} }
|
||||
|
||||
func New() *Validator {
|
||||
return &Validator{}
|
||||
func rejection() contracts.ValidationResult {
|
||||
return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCode, Message: "output rejected by always-reject validator"}
|
||||
}
|
||||
|
||||
func (v *Validator) Name() string {
|
||||
return Key
|
||||
}
|
||||
|
||||
func (v *Validator) ExecutionClass() contracts.ExecutionClass {
|
||||
func (v *ChunkValidator) Name() string { return Key }
|
||||
func (v *ChunkValidator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
|
||||
func (v *Validator) Validate(ctx context.Context, req contracts.ValidationRequest) (contracts.ValidationResult, error) {
|
||||
return contracts.ValidationResult{
|
||||
Approved: false,
|
||||
ReasonCode: ReasonCode,
|
||||
Message: "output rejected by always-reject validator",
|
||||
}, nil
|
||||
func (v *ChunkValidator) Validate(context.Context, contracts.ChunkValidationRequest) (contracts.ValidationResult, error) {
|
||||
return rejection(), nil
|
||||
}
|
||||
func (v *TypedValidator[T]) Name() string { return Key }
|
||||
func (v *TypedValidator[T]) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
func (v *TypedValidator[T]) Validate(context.Context, contracts.TypedValidationRequest[T]) (contracts.ValidationResult, error) {
|
||||
return rejection(), nil
|
||||
}
|
||||
func (v *legacyValidator) Name() string { return Key }
|
||||
func (v *legacyValidator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
func (v *legacyValidator) Validate(context.Context, contracts.ValidationRequest) (contracts.ValidationResult, error) {
|
||||
return rejection(), nil
|
||||
}
|
||||
|
||||
func Spec() pipeline.ValidatorSpec {
|
||||
return pipeline.ValidatorSpec{
|
||||
Key: Key,
|
||||
ExecutionClass: contracts.ExecutionClassDeterministic,
|
||||
}
|
||||
return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
|
||||
}
|
||||
|
||||
func Register(registry *pipeline.ValidatorRegistry) error {
|
||||
return registry.RegisterLegacyRawWithSpec(Spec(), func() (contracts.LegacyRawValidator, error) {
|
||||
return New(), nil
|
||||
if err := pipeline.RegisterChunkValidatorBuilder(registry, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.ChunkValidator, error) {
|
||||
options, err := DecodeOptions(request.Options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewChunk(options), nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return registry.RegisterLegacyRawBuilderWithSpec(Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.LegacyRawValidator, error) {
|
||||
if _, err := DecodeOptions(request.Options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &legacyValidator{}, nil
|
||||
})
|
||||
}
|
||||
func RegisterTyped[T any](registry *pipeline.ValidatorRegistry, kind contracts.ArtifactKind) error {
|
||||
return pipeline.RegisterTypedValidatorBuilder(registry, kind, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.TypedValidator[T], error) {
|
||||
options, err := DecodeOptions(request.Options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return NewTyped[T](options), nil
|
||||
})
|
||||
}
|
||||
func DecodeOptions(options map[string]any) (Options, error) {
|
||||
if err := pipeline.RejectUnknownOptions(options); err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
return Options{}, nil
|
||||
}
|
||||
func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
)
|
||||
|
||||
func TestValidatorRejects(t *testing.T) {
|
||||
result, err := New().Validate(context.Background(), contracts.ValidationRequest{})
|
||||
result, err := NewTyped[string](Options{}).Validate(context.Background(), contracts.TypedValidationRequest[string]{Value: "value"})
|
||||
if err != nil {
|
||||
t.Fatalf("Validate() error = %v, want nil", err)
|
||||
}
|
||||
|
||||
@@ -11,42 +11,73 @@ import (
|
||||
const Key = "generic/valid_json"
|
||||
const ReasonCodeInvalidJSON = "invalid_json"
|
||||
|
||||
var _ contracts.LegacyRawValidator = (*Validator)(nil)
|
||||
type Options struct{}
|
||||
|
||||
type Validator struct{}
|
||||
|
||||
func New() *Validator {
|
||||
return &Validator{}
|
||||
}
|
||||
type legacyValidator struct{}
|
||||
|
||||
func (v *Validator) Name() string {
|
||||
return Key
|
||||
}
|
||||
var _ contracts.SerializedValidator = (*Validator)(nil)
|
||||
var _ contracts.LegacyRawValidator = (*legacyValidator)(nil)
|
||||
|
||||
func New(Options) *Validator { return &Validator{} }
|
||||
|
||||
func (v *Validator) Name() string { return Key }
|
||||
|
||||
func (v *Validator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
|
||||
func (v *Validator) Validate(ctx context.Context, req contracts.ValidationRequest) (contracts.ValidationResult, error) {
|
||||
if !json.Valid(req.Payload.Content) {
|
||||
return contracts.ValidationResult{
|
||||
Approved: false,
|
||||
ReasonCode: ReasonCodeInvalidJSON,
|
||||
Message: "payload is not valid JSON",
|
||||
}, nil
|
||||
func (v *Validator) Validate(_ context.Context, req contracts.SerializedValidationRequest) (contracts.ValidationResult, error) {
|
||||
return validate(req.Content), nil
|
||||
}
|
||||
|
||||
func (v *legacyValidator) Name() string { return Key }
|
||||
|
||||
func (v *legacyValidator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
|
||||
func (v *legacyValidator) Validate(_ context.Context, req contracts.ValidationRequest) (contracts.ValidationResult, error) {
|
||||
return validate(req.Payload.Content), nil
|
||||
}
|
||||
|
||||
func validate(content []byte) contracts.ValidationResult {
|
||||
if !json.Valid(content) {
|
||||
return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCodeInvalidJSON, Message: "payload is not valid JSON"}
|
||||
}
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
return contracts.ValidationResult{Approved: true}
|
||||
}
|
||||
|
||||
func Spec() pipeline.ValidatorSpec {
|
||||
return pipeline.ValidatorSpec{
|
||||
Key: Key,
|
||||
ExecutionClass: contracts.ExecutionClassDeterministic,
|
||||
}
|
||||
return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
|
||||
}
|
||||
|
||||
func Register(registry *pipeline.ValidatorRegistry) error {
|
||||
return registry.RegisterLegacyRawWithSpec(Spec(), func() (contracts.LegacyRawValidator, error) {
|
||||
return New(), nil
|
||||
if err := pipeline.RegisterSerializedValidatorBuilder(registry, pipeline.SerializedValidatorSpec{
|
||||
ValidatorSpec: Spec(), SupportsChunks: true, SupportsArtifacts: true,
|
||||
}, validateOptions, func(request pipeline.BuildRequest) (contracts.SerializedValidator, error) {
|
||||
options, err := DecodeOptions(request.Options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(options), nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return registry.RegisterLegacyRawBuilderWithSpec(Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.LegacyRawValidator, error) {
|
||||
if _, err := DecodeOptions(request.Options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &legacyValidator{}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func DecodeOptions(options map[string]any) (Options, error) {
|
||||
if err := pipeline.RejectUnknownOptions(options); err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
return Options{}, nil
|
||||
}
|
||||
|
||||
func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }
|
||||
|
||||
@@ -15,7 +15,7 @@ func TestValidatorAcceptsValidJSON(t *testing.T) {
|
||||
`"value"`,
|
||||
}
|
||||
for _, payload := range tests {
|
||||
result, err := New().Validate(context.Background(), requestWithPayload(payload))
|
||||
result, err := New(Options{}).Validate(context.Background(), requestWithPayload(payload))
|
||||
if err != nil {
|
||||
t.Fatalf("Validate(%s) error = %v, want nil", payload, err)
|
||||
}
|
||||
@@ -26,7 +26,7 @@ func TestValidatorAcceptsValidJSON(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestValidatorRejectsInvalidJSON(t *testing.T) {
|
||||
result, err := New().Validate(context.Background(), requestWithPayload(`{"value":`))
|
||||
result, err := New(Options{}).Validate(context.Background(), requestWithPayload(`{"value":`))
|
||||
if err != nil {
|
||||
t.Fatalf("Validate() error = %v, want nil", err)
|
||||
}
|
||||
@@ -56,11 +56,6 @@ func TestSpecAndRegister(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func requestWithPayload(payload string) contracts.ValidationRequest {
|
||||
return contracts.ValidationRequest{
|
||||
Payload: contracts.RawPayload{
|
||||
Content: []byte(payload),
|
||||
MediaType: "application/json",
|
||||
},
|
||||
}
|
||||
func requestWithPayload(payload string) contracts.SerializedValidationRequest {
|
||||
return contracts.SerializedValidationRequest{Content: []byte(payload), MediaType: "application/json"}
|
||||
}
|
||||
|
||||
@@ -15,37 +15,40 @@ const Key = "generic/valid_json_schema"
|
||||
const ReasonCodeInvalidJSON = "invalid_json"
|
||||
const ReasonCodeSchemaInvalid = "json_schema_invalid"
|
||||
|
||||
var _ contracts.LegacyRawValidator = (*Validator)(nil)
|
||||
|
||||
type Options struct{}
|
||||
type Validator struct{}
|
||||
type legacyValidator struct{}
|
||||
|
||||
func New() *Validator {
|
||||
return &Validator{}
|
||||
}
|
||||
|
||||
func (v *Validator) Name() string {
|
||||
return Key
|
||||
}
|
||||
var _ contracts.SerializedValidator = (*Validator)(nil)
|
||||
var _ contracts.LegacyRawValidator = (*legacyValidator)(nil)
|
||||
|
||||
func New(Options) *Validator { return &Validator{} }
|
||||
func (v *Validator) Name() string { return Key }
|
||||
func (v *Validator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
|
||||
func (v *Validator) Validate(ctx context.Context, req contracts.ValidationRequest) (contracts.ValidationResult, error) {
|
||||
if len(req.Schema.JSONSchema) == 0 {
|
||||
func (v *Validator) Validate(_ context.Context, req contracts.SerializedValidationRequest) (contracts.ValidationResult, error) {
|
||||
return validate(req.Content, req.Schema.JSONSchema)
|
||||
}
|
||||
|
||||
func (v *legacyValidator) Name() string { return Key }
|
||||
func (v *legacyValidator) ExecutionClass() contracts.ExecutionClass {
|
||||
return contracts.ExecutionClassDeterministic
|
||||
}
|
||||
func (v *legacyValidator) Validate(_ context.Context, req contracts.ValidationRequest) (contracts.ValidationResult, error) {
|
||||
return validate(req.Payload.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")
|
||||
}
|
||||
|
||||
instance, err := jsonschema.UnmarshalJSON(bytes.NewReader(req.Payload.Content))
|
||||
instance, err := jsonschema.UnmarshalJSON(bytes.NewReader(content))
|
||||
if err != nil {
|
||||
return contracts.ValidationResult{
|
||||
Approved: false,
|
||||
ReasonCode: ReasonCodeInvalidJSON,
|
||||
Message: "payload is not valid JSON",
|
||||
}, nil
|
||||
return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCodeInvalidJSON, Message: "payload is not valid JSON"}, nil
|
||||
}
|
||||
|
||||
schemaDocument, err := jsonschema.UnmarshalJSON(bytes.NewReader(req.Schema.JSONSchema))
|
||||
schemaDocument, err := jsonschema.UnmarshalJSON(bytes.NewReader(schemaContent))
|
||||
if err != nil {
|
||||
return contracts.ValidationResult{}, fmt.Errorf("parse response schema: %w", err)
|
||||
}
|
||||
@@ -58,24 +61,39 @@ func (v *Validator) Validate(ctx context.Context, req contracts.ValidationReques
|
||||
return contracts.ValidationResult{}, fmt.Errorf("compile response schema: %w", err)
|
||||
}
|
||||
if err := schema.Validate(instance); err != nil {
|
||||
return contracts.ValidationResult{
|
||||
Approved: false,
|
||||
ReasonCode: ReasonCodeSchemaInvalid,
|
||||
Message: "payload does not conform to response schema",
|
||||
}, nil
|
||||
return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCodeSchemaInvalid, Message: "payload does not conform to response schema"}, nil
|
||||
}
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
|
||||
func Spec() pipeline.ValidatorSpec {
|
||||
return pipeline.ValidatorSpec{
|
||||
Key: Key,
|
||||
ExecutionClass: contracts.ExecutionClassDeterministic,
|
||||
}
|
||||
return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
|
||||
}
|
||||
|
||||
func Register(registry *pipeline.ValidatorRegistry) error {
|
||||
return registry.RegisterLegacyRawWithSpec(Spec(), func() (contracts.LegacyRawValidator, error) {
|
||||
return New(), nil
|
||||
if err := pipeline.RegisterSerializedValidatorBuilder(registry, pipeline.SerializedValidatorSpec{
|
||||
ValidatorSpec: Spec(), SupportsChunks: true, SupportsArtifacts: true,
|
||||
}, validateOptions, func(request pipeline.BuildRequest) (contracts.SerializedValidator, error) {
|
||||
options, err := DecodeOptions(request.Options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(options), nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return registry.RegisterLegacyRawBuilderWithSpec(Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.LegacyRawValidator, error) {
|
||||
if _, err := DecodeOptions(request.Options); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &legacyValidator{}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func DecodeOptions(options map[string]any) (Options, error) {
|
||||
if err := pipeline.RejectUnknownOptions(options); err != nil {
|
||||
return Options{}, err
|
||||
}
|
||||
return Options{}, nil
|
||||
}
|
||||
func validateOptions(options map[string]any) error { _, err := DecodeOptions(options); return err }
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
)
|
||||
|
||||
func TestValidatorAcceptsSchemaConformantJSON(t *testing.T) {
|
||||
result, err := New().Validate(context.Background(), requestWithSchema(`{"name":"Aria"}`, objectSchema()))
|
||||
result, err := New(Options{}).Validate(context.Background(), requestWithSchema(`{"name":"Aria"}`, objectSchema()))
|
||||
if err != nil {
|
||||
t.Fatalf("Validate() error = %v, want nil", err)
|
||||
}
|
||||
@@ -20,7 +20,7 @@ func TestValidatorAcceptsSchemaConformantJSON(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestValidatorRejectsInvalidPayloadJSON(t *testing.T) {
|
||||
result, err := New().Validate(context.Background(), requestWithSchema(`{"name":`, objectSchema()))
|
||||
result, err := New(Options{}).Validate(context.Background(), requestWithSchema(`{"name":`, objectSchema()))
|
||||
if err != nil {
|
||||
t.Fatalf("Validate() error = %v, want nil", err)
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func TestValidatorRejectsInvalidPayloadJSON(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestValidatorRejectsSchemaNonConformance(t *testing.T) {
|
||||
result, err := New().Validate(context.Background(), requestWithSchema(`{"name":3}`, objectSchema()))
|
||||
result, err := New(Options{}).Validate(context.Background(), requestWithSchema(`{"name":3}`, objectSchema()))
|
||||
if err != nil {
|
||||
t.Fatalf("Validate() error = %v, want nil", err)
|
||||
}
|
||||
@@ -46,7 +46,7 @@ func TestValidatorRejectsSchemaNonConformance(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestValidatorErrorsWhenSchemaContentMissing(t *testing.T) {
|
||||
_, err := New().Validate(context.Background(), requestWithSchema(`{"name":"Aria"}`, nil))
|
||||
_, err := New(Options{}).Validate(context.Background(), requestWithSchema(`{"name":"Aria"}`, nil))
|
||||
if err == nil {
|
||||
t.Fatal("Validate() error = nil, want missing schema content error")
|
||||
}
|
||||
@@ -56,7 +56,7 @@ func TestValidatorErrorsWhenSchemaContentMissing(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestValidatorErrorsWhenSchemaContentIsMalformed(t *testing.T) {
|
||||
_, err := New().Validate(context.Background(), requestWithSchema(`{"name":"Aria"}`, []byte(`{"type":`)))
|
||||
_, err := New(Options{}).Validate(context.Background(), requestWithSchema(`{"name":"Aria"}`, []byte(`{"type":`)))
|
||||
if err == nil {
|
||||
t.Fatal("Validate() error = nil, want malformed schema error")
|
||||
}
|
||||
@@ -83,18 +83,15 @@ func TestSpecAndRegister(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func requestWithSchema(payload string, schema []byte) contracts.ValidationRequest {
|
||||
return contracts.ValidationRequest{
|
||||
Schema: contracts.ResponseSchema{
|
||||
func requestWithSchema(payload string, schema []byte) contracts.SerializedValidationRequest {
|
||||
return contracts.SerializedValidationRequest{
|
||||
Schema: contracts.ArtifactSchema{
|
||||
ID: "test.schema",
|
||||
Name: "test_schema",
|
||||
Version: "v1",
|
||||
JSONSchema: append([]byte(nil), schema...),
|
||||
},
|
||||
Payload: contracts.RawPayload{
|
||||
Content: []byte(payload),
|
||||
MediaType: "application/json",
|
||||
},
|
||||
Content: []byte(payload), MediaType: "application/json",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user