package pipeline import ( "fmt" "strings" "gitea.maximumdirect.net/eric/notarius/internal/framework/contracts" ) type ChunkerConstructor func() (contracts.Chunker, error) type ChunkerRegistry struct { constructors map[string]ChunkerConstructor specs map[string]ModuleSpec } func NewChunkerRegistry() *ChunkerRegistry { return &ChunkerRegistry{ constructors: make(map[string]ChunkerConstructor), specs: make(map[string]ModuleSpec), } } func (r *ChunkerRegistry) Register(key string, constructor ChunkerConstructor) error { return r.RegisterWithSpec(defaultModuleSpec(key, StageChunk), constructor) } func (r *ChunkerRegistry) RegisterWithSpec(spec ModuleSpec, constructor ChunkerConstructor) error { if r == nil { return fmt.Errorf("chunker registry must not be nil") } normalizedSpec := normalizeModuleSpec(spec) if err := validateModuleSpec("chunker", StageChunk, normalizedSpec); err != nil { return err } if constructor == nil { return fmt.Errorf("chunker constructor for %q must not be nil", normalizedSpec.Key) } if _, ok := r.constructors[normalizedSpec.Key]; ok { return fmt.Errorf("chunker %q is already registered", normalizedSpec.Key) } if r.constructors == nil { r.constructors = make(map[string]ChunkerConstructor) } 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 *ChunkerRegistry) Build(key string) (contracts.Chunker, error) { if r == nil { return nil, fmt.Errorf("chunker registry must not be nil") } normalizedKey := strings.TrimSpace(key) if normalizedKey == "" { return nil, fmt.Errorf("chunker key must not be empty") } constructor, ok := r.constructors[normalizedKey] if !ok { return nil, fmt.Errorf("chunker %q is not registered", normalizedKey) } chunker, err := constructor() if err != nil { return nil, fmt.Errorf("build chunker %q: %w", normalizedKey, err) } if chunker == nil { return nil, fmt.Errorf("chunker %q constructor returned nil", normalizedKey) } if chunker.Key() != normalizedKey { return nil, fmt.Errorf("chunker %q returned key %q", normalizedKey, chunker.Key()) } return chunker, nil } func (r *ChunkerRegistry) 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 *ChunkerRegistry) RegisteredKeys() []string { if r == nil { return nil } return sortedRegistryKeys(r.constructors) }