Add D&D location occurrence validators
This commit is contained in:
@@ -0,0 +1,182 @@
|
||||
// Package invariants validates normalized D&D location occurrence artifacts.
|
||||
package invariants
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/shared/diagnostics"
|
||||
occurrenceshape "gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/validate/locationoccurrences/shape"
|
||||
)
|
||||
|
||||
const (
|
||||
Key = "normalize/dnd/location-occurrences/invariants"
|
||||
ReasonCode = "invalid_location_occurrence_normalization"
|
||||
policy = "dnd.location_occurrences.validator.normalized.v1"
|
||||
)
|
||||
|
||||
type Options struct{}
|
||||
type Validator struct{}
|
||||
|
||||
var _ contracts.TypedValidator[dnd.LocationOccurrenceList] = (*Validator)(nil)
|
||||
var _ pipeline.CheckpointFingerprintProvider = (*Validator)(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) CheckpointFingerprints() []pipeline.CheckpointFingerprint {
|
||||
return []pipeline.CheckpointFingerprint{{Name: "policy", Value: policy}}
|
||||
}
|
||||
|
||||
func (v *Validator) Validate(_ context.Context, req contracts.TypedValidationRequest[dnd.LocationOccurrenceList]) (contracts.ValidationResult, error) {
|
||||
if occurrenceshape.Validate(req.Value) != nil {
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
index := source.NewDocumentIndex(req.Source)
|
||||
if !allSourceRefsValid(index, req.Value) {
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
issues := issuesFor(shared.NewSourceRefOrderFromIndex(index), req.Value)
|
||||
if len(issues) == 0 {
|
||||
return contracts.ValidationResult{Approved: true}, nil
|
||||
}
|
||||
return contracts.ValidationResult{Approved: false, ReasonCode: ReasonCode, Message: diagnostics.Aggregate("invalid location occurrence normalization", issues)}, nil
|
||||
}
|
||||
|
||||
func allSourceRefsValid(index source.DocumentIndex, value dnd.LocationOccurrenceList) bool {
|
||||
for _, occurrence := range value.Occurrences {
|
||||
for _, ref := range occurrence.SourceRefs {
|
||||
if index.ValidateRef(ref) != nil {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func issuesFor(order shared.SourceRefOrder, value dnd.LocationOccurrenceList) []string {
|
||||
issues := make([]string, 0)
|
||||
for index, occurrence := range value.Occurrences {
|
||||
prefix := fmt.Sprintf("occurrences[%d]", index)
|
||||
for refIndex := 1; refIndex < len(occurrence.SourceRefs); refIndex++ {
|
||||
previous, current := occurrence.SourceRefs[refIndex-1], occurrence.SourceRefs[refIndex]
|
||||
if order.Less(current, previous) {
|
||||
issues = append(issues, fmt.Sprintf("%s.source_refs are not in canonical order at index %d", prefix, refIndex))
|
||||
} else if current == previous {
|
||||
issues = append(issues, fmt.Sprintf("%s.source_refs[%d] duplicates the previous reference", prefix, refIndex))
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sort.SliceIsSorted(value.Occurrences, func(left, right int) bool {
|
||||
return lessOccurrence(order, value.Occurrences[left], value.Occurrences[right])
|
||||
}) {
|
||||
issues = append(issues, "occurrences are not in canonical order")
|
||||
}
|
||||
seen := make(map[string]int)
|
||||
for index, occurrence := range value.Occurrences {
|
||||
key := exactIdentity(occurrence)
|
||||
if previous, ok := seen[key]; ok {
|
||||
issues = append(issues, fmt.Sprintf("occurrences[%d] duplicates occurrence %d", index, previous))
|
||||
continue
|
||||
}
|
||||
seen[key] = index
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
func lessOccurrence(order shared.SourceRefOrder, left, right dnd.LocationOccurrence) bool {
|
||||
leftPosition, leftHasEvidence := order.EarliestValid(left.SourceRefs)
|
||||
rightPosition, rightHasEvidence := order.EarliestValid(right.SourceRefs)
|
||||
if leftHasEvidence != rightHasEvidence {
|
||||
return leftHasEvidence
|
||||
}
|
||||
if leftHasEvidence && leftPosition != rightPosition {
|
||||
return leftPosition < rightPosition
|
||||
}
|
||||
if left.LocationID != right.LocationID {
|
||||
return left.LocationID < right.LocationID
|
||||
}
|
||||
if left.Name != right.Name {
|
||||
return left.Name < right.Name
|
||||
}
|
||||
if kindOrder(left.Kind) != kindOrder(right.Kind) {
|
||||
return kindOrder(left.Kind) < kindOrder(right.Kind)
|
||||
}
|
||||
if left.Kind != right.Kind {
|
||||
return left.Kind < right.Kind
|
||||
}
|
||||
return sourceRefsLess(order, left.SourceRefs, right.SourceRefs)
|
||||
}
|
||||
func kindOrder(kind dnd.LocationOccurrenceKind) int {
|
||||
switch kind {
|
||||
case dnd.LocationOccurrenceKindVisited:
|
||||
return 0
|
||||
case dnd.LocationOccurrenceKindPlanned:
|
||||
return 1
|
||||
case dnd.LocationOccurrenceKindRecalled:
|
||||
return 2
|
||||
case dnd.LocationOccurrenceKindMentioned:
|
||||
return 3
|
||||
default:
|
||||
return 4
|
||||
}
|
||||
}
|
||||
func sourceRefsLess(order shared.SourceRefOrder, left, right []source.SourceRef) bool {
|
||||
for index := 0; index < len(left) && index < len(right); index++ {
|
||||
if left[index] != right[index] {
|
||||
return order.Less(left[index], right[index])
|
||||
}
|
||||
}
|
||||
return len(left) < len(right)
|
||||
}
|
||||
func exactIdentity(occurrence dnd.LocationOccurrence) string {
|
||||
var key strings.Builder
|
||||
writeKeyString(&key, occurrence.LocationID)
|
||||
writeKeyString(&key, occurrence.Name)
|
||||
writeKeyString(&key, string(occurrence.Kind))
|
||||
for _, ref := range occurrence.SourceRefs {
|
||||
writeKeyString(&key, ref.SourceID)
|
||||
writeKeyInt(&key, ref.StartUnitID)
|
||||
writeKeyInt(&key, ref.EndUnitID)
|
||||
}
|
||||
return key.String()
|
||||
}
|
||||
func writeKeyString(builder *strings.Builder, value string) {
|
||||
builder.WriteString(strconv.Itoa(len(value)))
|
||||
builder.WriteByte(':')
|
||||
builder.WriteString(value)
|
||||
}
|
||||
func writeKeyInt(builder *strings.Builder, value int) {
|
||||
builder.WriteString(strconv.Itoa(value))
|
||||
builder.WriteByte(';')
|
||||
}
|
||||
|
||||
func Spec() pipeline.ValidatorSpec {
|
||||
return pipeline.ValidatorSpec{Key: Key, ExecutionClass: contracts.ExecutionClassDeterministic}
|
||||
}
|
||||
func Register(registry *pipeline.ValidatorRegistry) error {
|
||||
return pipeline.RegisterTypedValidatorBuilder(registry, dnd.LocationOccurrenceListKind, Spec(), validateOptions, func(request pipeline.BuildRequest) (contracts.TypedValidator[dnd.LocationOccurrenceList], error) {
|
||||
options, err := DecodeOptions(request.Options)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return New(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 }
|
||||
@@ -0,0 +1,77 @@
|
||||
package invariants
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
)
|
||||
|
||||
func TestValidatorApprovesCanonicalOrderForEveryKind(t *testing.T) {
|
||||
kinds := []dnd.LocationOccurrenceKind{dnd.LocationOccurrenceKindVisited, dnd.LocationOccurrenceKindPlanned, dnd.LocationOccurrenceKindRecalled, dnd.LocationOccurrenceKindMentioned}
|
||||
occurrences := make([]dnd.LocationOccurrence, len(kinds))
|
||||
for index, kind := range kinds {
|
||||
occurrences[index] = occurrence(kind, 1)
|
||||
}
|
||||
result, err := New(Options{}).Validate(context.Background(), request(dnd.LocationOccurrenceList{Occurrences: occurrences}))
|
||||
if err != nil || !result.Approved {
|
||||
t.Fatalf("Validate() = %#v, %v", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatorRejectsOrderingAndExactDuplicateInvariants(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
value dnd.LocationOccurrenceList
|
||||
want string
|
||||
}{
|
||||
{"references", dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{{LocationID: "id", Name: "Moon Gate", Kind: dnd.LocationOccurrenceKindVisited, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 2, EndUnitID: 2}, {SourceID: "session", StartUnitID: 1, EndUnitID: 1}}}}}, "not in canonical order"},
|
||||
{"list", dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{occurrence(dnd.LocationOccurrenceKindVisited, 2), occurrence(dnd.LocationOccurrenceKindVisited, 1)}}, "occurrences are not in canonical order"},
|
||||
{"duplicate", dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{occurrence(dnd.LocationOccurrenceKindVisited, 1), occurrence(dnd.LocationOccurrenceKindVisited, 1)}}, "duplicates occurrence"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
result, err := New(Options{}).Validate(context.Background(), request(test.value))
|
||||
if err != nil || result.Approved || result.ReasonCode != ReasonCode || !strings.Contains(result.Message, test.want) {
|
||||
t.Fatalf("Validate() = %#v, %v", result, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatorDefersInvalidEvidenceAndDoesNotMutate(t *testing.T) {
|
||||
value := dnd.LocationOccurrenceList{Occurrences: []dnd.LocationOccurrence{{LocationID: "id", Name: "Moon Gate", Kind: dnd.LocationOccurrenceKindVisited, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: 99, EndUnitID: 99}}}}}
|
||||
before := cloneList(value)
|
||||
result, err := New(Options{}).Validate(context.Background(), request(value))
|
||||
if err != nil || !result.Approved || !reflect.DeepEqual(value, before) {
|
||||
t.Fatalf("invalid evidence deferral = %#v, %v", result, err)
|
||||
}
|
||||
registry := pipeline.NewValidatorRegistry()
|
||||
if err := Register(registry); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := New(Options{}).CheckpointFingerprints(); len(got) != 1 || got[0].Value != policy {
|
||||
t.Fatalf("fingerprints = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func request(value dnd.LocationOccurrenceList) contracts.TypedValidationRequest[dnd.LocationOccurrenceList] {
|
||||
return contracts.TypedValidationRequest[dnd.LocationOccurrenceList]{Source: document(), Value: value}
|
||||
}
|
||||
func document() *source.SourceDocument {
|
||||
return &source.SourceDocument{ID: "session", Units: []source.SourceUnit{{ID: 1}, {ID: 2}}}
|
||||
}
|
||||
func occurrence(kind dnd.LocationOccurrenceKind, unit int) dnd.LocationOccurrence {
|
||||
return dnd.LocationOccurrence{LocationID: "id", Name: "Moon Gate", Kind: kind, SourceRefs: []source.SourceRef{{SourceID: "session", StartUnitID: unit, EndUnitID: unit}}}
|
||||
}
|
||||
func cloneList(value dnd.LocationOccurrenceList) dnd.LocationOccurrenceList {
|
||||
cloned := dnd.LocationOccurrenceList{Occurrences: append([]dnd.LocationOccurrence(nil), value.Occurrences...)}
|
||||
for index := range cloned.Occurrences {
|
||||
cloned.Occurrences[index].SourceRefs = append([]source.SourceRef(nil), value.Occurrences[index].SourceRefs...)
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
Reference in New Issue
Block a user