package pipeline import ( "fmt" "strings" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" ) type ValidatorConstructor func() (contracts.Validator, error) type ValidatorRegistry struct { constructors map[string]ValidatorConstructor specs map[string]ModuleSpec } func NewValidatorRegistry() *ValidatorRegistry { return &ValidatorRegistry{ constructors: make(map[string]ValidatorConstructor), specs: make(map[string]ModuleSpec), } } func (r *ValidatorRegistry) Register(key string, constructor ValidatorConstructor) error { return r.RegisterWithSpec(defaultModuleSpec(key, StageValidate), constructor) } func (r *ValidatorRegistry) RegisterWithSpec(spec ModuleSpec, constructor ValidatorConstructor) error { if r == nil { return fmt.Errorf("validator registry must not be nil") } normalizedSpec := normalizeModuleSpec(spec) if err := validateModuleSpec("validator", StageValidate, normalizedSpec); err != nil { return err } if constructor == nil { return fmt.Errorf("validator constructor for %q must not be nil", normalizedSpec.Key) } if _, ok := r.constructors[normalizedSpec.Key]; ok { return fmt.Errorf("validator %q is already registered", normalizedSpec.Key) } if r.constructors == nil { r.constructors = make(map[string]ValidatorConstructor) } if r.specs == nil { r.specs = make(map[string]ModuleSpec) } r.constructors[normalizedSpec.Key] = constructor r.specs[normalizedSpec.Key] = cloneModuleSpec(normalizedSpec) return nil } func (r *ValidatorRegistry) Build(key string) (contracts.Validator, error) { if r == nil { return nil, fmt.Errorf("validator registry must not be nil") } normalizedKey := strings.TrimSpace(key) if normalizedKey == "" { return nil, fmt.Errorf("validator key must not be empty") } constructor, ok := r.constructors[normalizedKey] if !ok { return nil, fmt.Errorf("validator %q is not registered", normalizedKey) } validator, err := constructor() if err != nil { return nil, fmt.Errorf("build validator %q: %w", normalizedKey, err) } if validator == nil { return nil, fmt.Errorf("validator %q constructor returned nil", normalizedKey) } if validator.Name() != normalizedKey { return nil, fmt.Errorf("validator %q returned name %q", normalizedKey, validator.Name()) } return validator, nil } func (r *ValidatorRegistry) Spec(key string) (ModuleSpec, bool) { if r == nil { return ModuleSpec{}, false } spec, ok := r.specs[strings.TrimSpace(key)] if !ok { return ModuleSpec{}, false } return cloneModuleSpec(spec), true } func (r *ValidatorRegistry) RegisteredKeys() []string { if r == nil { return nil } return sortedRegistryKeys(r.constructors) }