registry.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package plugin
  2. import (
  3. "fmt"
  4. "sync"
  5. )
  6. // Registry holds all registered collector plugins.
  7. type Registry struct {
  8. mu sync.RWMutex
  9. plugins map[string]Collector
  10. }
  11. // NewRegistry creates an empty plugin registry.
  12. func NewRegistry() *Registry {
  13. return &Registry{plugins: make(map[string]Collector)}
  14. }
  15. // Register adds a collector to the registry. Panics on duplicate name.
  16. func (r *Registry) Register(c Collector) {
  17. r.mu.Lock()
  18. defer r.mu.Unlock()
  19. name := c.Name()
  20. if _, exists := r.plugins[name]; exists {
  21. panic(fmt.Sprintf("plugin %q already registered", name))
  22. }
  23. r.plugins[name] = c
  24. }
  25. // Get returns a collector by name, or an error if not found.
  26. func (r *Registry) Get(name string) (Collector, error) {
  27. r.mu.RLock()
  28. defer r.mu.RUnlock()
  29. c, ok := r.plugins[name]
  30. if !ok {
  31. return nil, fmt.Errorf("plugin %q not registered", name)
  32. }
  33. return c, nil
  34. }
  35. // List returns all registered plugin names.
  36. func (r *Registry) List() []string {
  37. r.mu.RLock()
  38. defer r.mu.RUnlock()
  39. names := make([]string, 0, len(r.plugins))
  40. for name := range r.plugins {
  41. names = append(names, name)
  42. }
  43. return names
  44. }