registry

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2025 License: MIT Imports: 9 Imported by: 0

README ΒΆ

πŸ—ƒοΈ Registry Package

A flexible, extensible registry system for managing entities with support for caching, persistence, validation, events, and metrics.

Features

  • Flexible Entity Management: Register, retrieve, update, and unregister entities
  • Caching: Built-in memory caching with TTL support
  • Persistence: File-based persistence with automatic save/load
  • Validation: Customizable validation rules for entities and metadata
  • Events: Event-driven architecture with observer pattern
  • Metrics: Built-in metrics collection and monitoring
  • Health Monitoring: Health status tracking and error reporting
  • Search: Full-text search and metadata-based filtering
  • Lifecycle Management: Activate/deactivate entities
  • Thread Safety: Concurrent access support with proper locking

Architecture


🧰 Usage Examples

πŸ§ͺ Registering an Entity
user := registry.NewBaseEntity("user-1", "John Doe")
user.Metadata()["email"] = "john@example.com"
err := registry.Register(ctx, user)
πŸ§ͺ Custom Registry with Caching & Persistence
reg, err := registry.NewRegistryBuilder().
    WithName("prod-reg").
    WithCache(1000, 10*time.Minute).
    WithPersistence("/data/entities.json", 30*time.Second).
    BuildRegistry()

πŸ… Best Practices

  • Use property-style getters (e.g., Name(), not GetName())
  • Prefer registry interfaces for dependency inversion
  • Leverage event bus and observer for decoupled side effects
  • Use the builder for complex configuration

πŸ“„ References

Documentation ΒΆ

Overview ΒΆ

Example ΒΆ

Example demonstrates basic registry usage

// Create a new registry
registry := New()

// Register some entities
registry.Register("user-1", Meta{
	Name:     "John Doe",
	Active:   true,
	Metadata: map[string]string{"email": "john@example.com", "role": "admin"},
})

registry.Register("user-2", Meta{
	Name:     "Jane Smith",
	Active:   true,
	Metadata: map[string]string{"email": "jane@example.com", "role": "user"},
})

// Get an entity
user := registry.Get("user-1")
fmt.Printf("User: %s (%s)\n", user.Name, user.Metadata["email"])

// Check if registered
fmt.Printf("User-1 registered: %t\n", registry.IsRegistered("user-1"))

// List all registered entities
registered := registry.ListRegistered()
fmt.Printf("Total registered: %d\n", len(registered))

// List active entities
active := registry.ListActive()
fmt.Printf("Active entities: %d\n", len(active))

// Get metadata
email, found := registry.GetMetadata("user-1", "email")
fmt.Printf("Email found: %t, value: %s\n", found, email)

// Set metadata
registry.SetMetadata("user-1", "last_login", time.Now().Format(time.RFC3339))

// Count entities
fmt.Printf("Total count: %d\n", registry.Count())

// Unregister an entity
removed := registry.Unregister("user-2")
fmt.Printf("User-2 removed: %t\n", removed)
Output:

User: John Doe (john@example.com)
User-1 registered: true
Total registered: 2
Active entities: 2
Email found: true, value: john@example.com
Total count: 2
User-2 removed: true
Example (Fourth) ΒΆ

Example_fourth demonstrates entity lifecycle management

registry := New()

// Register an entity
registry.Register("entity-1", Meta{
	Name:     "Test Entity",
	Active:   true,
	Metadata: map[string]string{"version": "1.0"},
})

fmt.Printf("Initial count: %d\n", registry.Count())

// Deactivate by setting Active to false
entity := registry.Get("entity-1")
entity.Active = false
registry.Register("entity-1", entity)

fmt.Printf("Active entities: %d\n", len(registry.ListActive()))

// Reactivate
entity.Active = true
registry.Register("entity-1", entity)

fmt.Printf("Active entities after reactivation: %d\n", len(registry.ListActive()))

// Unregister
removed := registry.Unregister("entity-1")
fmt.Printf("Removed: %t, Final count: %d\n", removed, registry.Count())
Output:

Initial count: 1
Active entities: 0
Active entities after reactivation: 1
Removed: true, Final count: 0
Example (Second) ΒΆ

Example_second demonstrates global registry functions

// Reset the global registry to ensure a clean state for the example
globalRegistry = New() // This avoids pollution from other tests/examples

// Use global registry functions
Register("global-user", Meta{
	Name:     "Global User",
	Active:   true,
	Metadata: map[string]string{"type": "global"},
})

// Get from global registry
user := Get("global-user")
fmt.Printf("Global user: %s\n", user.Name)

// Check registration
fmt.Printf("Is registered: %t\n", IsRegistered("global-user"))

// List all
all := ListRegistered()
fmt.Printf("Global registry count: %d\n", len(all))

// Set metadata
SetMetadata("global-user", "status", "active")

// Get metadata
status, found := GetMetadata("global-user", "status")
fmt.Printf("Status: %s (found: %t)\n", status, found)
Output:

Global user: Global User
Is registered: true
Global registry count: 1
Status: active (found: true)
Example (Third) ΒΆ

Example_third demonstrates metadata operations

registry := New()

// Register with metadata
registry.Register("product-1", Meta{
	Name:   "Laptop",
	Active: true,
	Metadata: map[string]string{
		"category": "Electronics",
		"price":    "999.99",
		"brand":    "TechCorp",
	},
})

// Get specific metadata
category, found := registry.GetMetadata("product-1", "category")
fmt.Printf("Category: %s (found: %t)\n", category, found)

price, found := registry.GetMetadata("product-1", "price")
fmt.Printf("Price: %s (found: %t)\n", price, found)

// Set new metadata
registry.SetMetadata("product-1", "in_stock", "true")
registry.SetMetadata("product-1", "warranty", "2 years")

// Get updated metadata
stock, found := registry.GetMetadata("product-1", "in_stock")
fmt.Printf("In stock: %s (found: %t)\n", stock, found)

// Try to get non-existent metadata
nonExistent, found := registry.GetMetadata("product-1", "non_existent")
fmt.Printf("Non-existent: %s (found: %t)\n", nonExistent, found)
Output:

Category: Electronics (found: true)
Price: 999.99 (found: true)
In stock: true (found: true)
Non-existent:  (found: false)

Index ΒΆ

Examples ΒΆ

Constants ΒΆ

View Source
const (
	EventEntityRegistered   = "entity_registered"
	EventEntityUnregistered = "entity_unregistered"
	EventEntityUpdated      = "entity_updated"
	EventEntityActivated    = "entity_activated"
	EventEntityDeactivated  = "entity_deactivated"
)

RegistryEventType constants

Variables ΒΆ

This section is empty.

Functions ΒΆ

func Count ΒΆ

func Count() int

func GetMetadata ΒΆ

func GetMetadata(id, key string) (string, bool)

func IsRegistered ΒΆ

func IsRegistered(id string) bool

func ListActive ΒΆ

func ListActive() []string

func ListRegistered ΒΆ

func ListRegistered() []string

func NewRedisClient ΒΆ

func NewRedisClient(url string) (*redis.Client, error)

NewRedisClient creates a new Redis client from a URL

func Register ΒΆ

func Register(id string, meta Meta)

Global convenience functions

func SetMetadata ΒΆ

func SetMetadata(id, key, value string) bool

func Unregister ΒΆ

func Unregister(id string) bool

Types ΒΆ

type BaseEntity ΒΆ

type BaseEntity struct {
	BEId        string            `json:"id"`
	BEName      string            `json:"name"`
	BEActive    bool              `json:"active"`
	BEMetadata  map[string]string `json:"metadata,omitempty"`
	BECreatedAt time.Time         `json:"created_at"`
	BEUpdatedAt time.Time         `json:"updated_at"`
}

BaseEntity provides a default implementation of the Entity interface

func NewBaseEntity ΒΆ

func NewBaseEntity(id, name string) *BaseEntity

NewBaseEntity creates a new base entity

func (*BaseEntity) Active ΒΆ

func (e *BaseEntity) Active() bool

func (*BaseEntity) CreatedAt ΒΆ

func (e *BaseEntity) CreatedAt() time.Time

func (*BaseEntity) ID ΒΆ

func (e *BaseEntity) ID() string

Property-style getter methods to implement Entity interface

func (*BaseEntity) Metadata ΒΆ

func (e *BaseEntity) Metadata() map[string]string

func (*BaseEntity) Name ΒΆ

func (e *BaseEntity) Name() string

func (*BaseEntity) UpdatedAt ΒΆ

func (e *BaseEntity) UpdatedAt() time.Time

type Builder ΒΆ

type Builder struct {
	// contains filtered or unexported fields
}

Builder provides a fluent interface for building registry configurations

func NewBuilder ΒΆ

func NewBuilder() *Builder

NewBuilder creates a new registry builder

func (*Builder) Build ΒΆ

func (b *Builder) Build() Config

Build returns the built configuration

func (*Builder) BuildRegistry ΒΆ

func (b *Builder) BuildRegistry() (Provider, error)

BuildRegistry creates a registry with the built configuration

func (*Builder) WithCache ΒΆ

func (b *Builder) WithCache(size int, ttl time.Duration) *Builder

WithCache sets cache configuration

func (*Builder) WithDefaultTTL ΒΆ

func (b *Builder) WithDefaultTTL(ttl time.Duration) *Builder

WithDefaultTTL sets the default TTL for entities

func (*Builder) WithKeyPrefix ΒΆ

func (b *Builder) WithKeyPrefix(prefix string) *Builder

WithKeyPrefix sets the Redis key prefix for the registry

func (*Builder) WithMaxEntities ΒΆ

func (b *Builder) WithMaxEntities(max int) *Builder

WithMaxEntities sets the maximum number of entities

func (*Builder) WithName ΒΆ

func (b *Builder) WithName(name string) *Builder

WithName sets the registry name

func (*Builder) WithPersistence ΒΆ

func (b *Builder) WithPersistence(path string, interval time.Duration) *Builder

WithPersistence enables persistence with the given path

func (*Builder) WithRedis ΒΆ

func (b *Builder) WithRedis(url string) *Builder

WithRedis configures Redis cache settings

func (*Builder) WithRedisAdvanced ΒΆ

func (b *Builder) WithRedisAdvanced(
	url string,
	prefix string,
	poolSize int,
	minIdleConns int,
	maxRetries int,
	dialTimeout time.Duration,
	readTimeout time.Duration,
	writeTimeout time.Duration,
) *Builder

WithRedisAdvanced allows fine-grained Redis configuration

func (*Builder) WithValidation ΒΆ

func (b *Builder) WithValidation(required, forbidden []string) *Builder

WithValidation sets validation configuration

type Cache ΒΆ

type Cache interface {
	Get(ctx context.Context, id string) (Entity, bool)
	Set(ctx context.Context, entity Entity) error
	Delete(ctx context.Context, id string) error
	Clear(ctx context.Context) error
	Size() int
}

Cache defines the interface for registry caching

type Config ΒΆ

type Config struct {
	Name             string        `json:"name"`
	MaxEntities      int           `json:"max_entities"`
	DefaultTTL       time.Duration `json:"default_ttl"`
	EnableEvents     bool          `json:"enable_events"`
	EnableValidation bool          `json:"enable_validation"`

	// Cache settings
	CacheSize int           `json:"cache_size"`
	CacheTTL  time.Duration `json:"cache_ttl"`

	// Redis cache settings
	RedisURL          string        `json:"redis_url"`            // Redis server URL
	RedisKeyPrefix    string        `json:"redis_key_prefix"`     // Prefix for Redis keys
	RedisPoolSize     int           `json:"redis_pool_size"`      // Max connections in pool
	RedisMinIdleConns int           `json:"redis_min_idle_conns"` // Min idle connections
	RedisMaxRetries   int           `json:"redis_max_retries"`    // Max retries for commands
	RedisDialTimeout  time.Duration `json:"redis_dial_timeout"`   // Dial timeout
	RedisReadTimeout  time.Duration `json:"redis_read_timeout"`   // Read timeout
	RedisWriteTimeout time.Duration `json:"redis_write_timeout"`  // Write timeout

	// Advanced features
	EnableCompression bool   `json:"enable_compression"`
	EnablePersistence bool   `json:"enable_persistence"`
	PersistencePath   string `json:"persistence_path"`

	// Auto-save settings
	AutoSaveInterval time.Duration `json:"auto_save_interval"`

	// Metadata validation
	RequiredMetadata   []string                      `json:"required_metadata"`
	ForbiddenMetadata  []string                      `json:"forbidden_metadata"`
	MetadataValidators map[string]func(string) error `json:"-"`
}

Config holds configuration for registry implementations

type Enhanced ΒΆ

type Enhanced struct {
	// contains filtered or unexported fields
}

Enhanced provides a full-featured registry implementation

func NewEnhanced ΒΆ

func NewEnhanced(config Config) *Enhanced

NewEnhanced creates a new enhanced registry

func (*Enhanced) Activate ΒΆ

func (r *Enhanced) Activate(ctx context.Context, id string) error

Activate activates an entity

func (*Enhanced) AddObserver ΒΆ

func (r *Enhanced) AddObserver(observer Observer)

AddObserver adds an observer to the registry

func (*Enhanced) Count ΒΆ

func (r *Enhanced) Count(ctx context.Context) (int, error)

Count returns the total number of entities

func (*Enhanced) CountActive ΒΆ

func (r *Enhanced) CountActive(ctx context.Context) (int, error)

CountActive returns the number of active entities

func (*Enhanced) Deactivate ΒΆ

func (r *Enhanced) Deactivate(ctx context.Context, id string) error

Deactivate deactivates an entity

func (*Enhanced) Get ΒΆ

func (r *Enhanced) Get(ctx context.Context, id string) (Entity, error)

Get retrieves an entity by ID

func (*Enhanced) GetMetadata ΒΆ

func (r *Enhanced) GetMetadata(ctx context.Context, id, key string) (string, error)

GetMetadata retrieves specific metadata for an entity

func (*Enhanced) IsRegistered ΒΆ

func (r *Enhanced) IsRegistered(ctx context.Context, id string) bool

IsRegistered checks if an entity is registered

func (*Enhanced) List ΒΆ

func (r *Enhanced) List(ctx context.Context) ([]Entity, error)

List returns all entities

func (*Enhanced) ListActive ΒΆ

func (r *Enhanced) ListActive(ctx context.Context) ([]Entity, error)

ListActive returns all active entities

func (*Enhanced) ListByMetadata ΒΆ

func (r *Enhanced) ListByMetadata(
	ctx context.Context,
	key, value string,
) ([]Entity, error)

ListByMetadata returns entities with specific metadata

func (*Enhanced) Register ΒΆ

func (r *Enhanced) Register(ctx context.Context, entity Entity) error

Register adds or updates an entity in the registry

func (*Enhanced) RemoveMetadata ΒΆ

func (r *Enhanced) RemoveMetadata(ctx context.Context, id, key string) error

RemoveMetadata removes specific metadata from an entity

func (*Enhanced) RemoveObserver ΒΆ

func (r *Enhanced) RemoveObserver(observer Observer)

RemoveObserver removes an observer from the registry

func (*Enhanced) Search ΒΆ

func (r *Enhanced) Search(ctx context.Context, query string) ([]Entity, error)

Search performs a simple search on entity names

func (*Enhanced) SearchByMetadata ΒΆ

func (r *Enhanced) SearchByMetadata(
	ctx context.Context,
	metadata map[string]string,
) ([]Entity, error)

SearchByMetadata searches entities by metadata

func (*Enhanced) SetMetadata ΒΆ

func (r *Enhanced) SetMetadata(ctx context.Context, id, key, value string) error

SetMetadata sets specific metadata for an entity

func (*Enhanced) Unregister ΒΆ

func (r *Enhanced) Unregister(ctx context.Context, id string) error

Unregister removes an entity from the registry

func (*Enhanced) WithCache ΒΆ

func (r *Enhanced) WithCache(cache Cache) *Enhanced

WithCache sets the cache for the registry

func (*Enhanced) WithEventBus ΒΆ

func (r *Enhanced) WithEventBus(eventBus EventBus) *Enhanced

WithEventBus sets the event bus for the registry

func (*Enhanced) WithHealth ΒΆ

func (r *Enhanced) WithHealth(health Health) *Enhanced

WithHealth sets the health checker for the registry

func (*Enhanced) WithMetrics ΒΆ

func (r *Enhanced) WithMetrics(metrics Metrics) *Enhanced

WithMetrics sets the metrics collector for the registry

func (*Enhanced) WithPersistence ΒΆ

func (r *Enhanced) WithPersistence(persistence Persistence) *Enhanced

WithPersistence sets the persistence layer for the registry

func (*Enhanced) WithValidator ΒΆ

func (r *Enhanced) WithValidator(validator Validator) *Enhanced

WithValidator sets the validator for the registry

type Entity ΒΆ

type Entity interface {
	ID() string
	Name() string
	Active() bool
	Metadata() map[string]string
	CreatedAt() time.Time
	UpdatedAt() time.Time
}

Entity represents any entity that can be registered

type Event ΒΆ

type Event struct {
	Type      string                 `json:"type"`
	EntityID  string                 `json:"entity_id"`
	Entity    Entity                 `json:"entity,omitempty"`
	Timestamp time.Time              `json:"timestamp"`
	Metadata  map[string]interface{} `json:"metadata,omitempty"`
}

Event represents a registry event

type EventBus ΒΆ

type EventBus interface {
	Subscribe(observer Observer) error
	Unsubscribe(observer Observer) error
	Emit(ctx context.Context, event Event) error
}

EventBus defines the interface for registry event handling

type Factory ΒΆ

type Factory interface {
	Create(
		ctx context.Context,
		config Config,
	) (Provider, error)
	CreateWithPersistence(
		ctx context.Context,
		config Config,
		persistence Persistence,
	) (Provider, error)
	CreateWithCache(
		ctx context.Context,
		config Config,
		cache Cache,
	) (Provider, error)
	CreateWithMetrics(
		ctx context.Context,
		config Config,
		metrics Metrics,
	) (Provider, error)
}

Factory defines the interface for creating registry instances

func NewRegistryFactory ΒΆ

func NewRegistryFactory() Factory

NewRegistryFactory creates a new registry factory

type FactoryImpl ΒΆ

type FactoryImpl struct{}

FactoryImpl implements RegistryFactory

func (*FactoryImpl) Create ΒΆ

func (f *FactoryImpl) Create(
	ctx context.Context,
	config Config,
) (Provider, error)

Create creates a basic registry with the given configuration

func (*FactoryImpl) CreateForDevelopment ΒΆ

func (f *FactoryImpl) CreateForDevelopment(
	ctx context.Context,
	name string,
) (Provider, error)

CreateForDevelopment creates a registry with development-friendly defaults, including in-memory storage and verbose logging.

func (*FactoryImpl) CreateForProduction ΒΆ

func (f *FactoryImpl) CreateForProduction(
	ctx context.Context,
	name string,
	persistencePath string,
) (Provider, error)

CreateForProduction creates a registry optimized for production use

func (*FactoryImpl) CreateForTesting ΒΆ

func (f *FactoryImpl) CreateForTesting(ctx context.Context) (Provider, error)

CreateForTesting creates a registry optimized for testing

func (*FactoryImpl) CreateFullFeatured ΒΆ

func (f *FactoryImpl) CreateFullFeatured(
	ctx context.Context,
	config Config,
) (Provider, error)

CreateFullFeatured creates a registry with all features enabled, including persistence, caching, metrics, and validation.

func (*FactoryImpl) CreateWithCache ΒΆ

func (f *FactoryImpl) CreateWithCache(
	ctx context.Context,
	config Config,
	cache Cache,
) (Provider, error)

CreateWithCache creates a registry with custom cache

func (*FactoryImpl) CreateWithMetrics ΒΆ

func (f *FactoryImpl) CreateWithMetrics(
	ctx context.Context,
	config Config,
	metrics Metrics,
) (Provider, error)

CreateWithMetrics creates a registry with metrics

func (*FactoryImpl) CreateWithPersistence ΒΆ

func (f *FactoryImpl) CreateWithPersistence(
	ctx context.Context,
	config Config,
	persistence Persistence,
) (Provider, error)

CreateWithPersistence creates a registry with persistence

func (*FactoryImpl) CreateWithRedisCache ΒΆ

func (f *FactoryImpl) CreateWithRedisCache(
	ctx context.Context,
	config Config,
	redisURL string,
) (Provider, error)

CreateWithRedisCache creates a registry with Redis cache

type FilePersistence ΒΆ

type FilePersistence struct {
	// contains filtered or unexported fields
}

FilePersistence implements RegistryPersistence using file storage

func NewFilePersistence ΒΆ

func NewFilePersistence(filePath string) *FilePersistence

NewFilePersistence creates a new file persistence layer

func (*FilePersistence) Clear ΒΆ

func (p *FilePersistence) Clear(ctx context.Context) error

Clear removes the persistence file

func (*FilePersistence) Delete ΒΆ

func (p *FilePersistence) Delete(ctx context.Context, id string) error

Delete removes the persistence file

func (*FilePersistence) Load ΒΆ

func (p *FilePersistence) Load(ctx context.Context) ([]Entity, error)

Load loads entities from file

func (*FilePersistence) Save ΒΆ

func (p *FilePersistence) Save(ctx context.Context, entities []Entity) error

Save persists entities to file

type Health ΒΆ

type Health interface {
	IsHealthy(ctx context.Context) bool
	GetHealthStatus(ctx context.Context) map[string]interface{}
	GetLastError() error
}

Health defines the interface for registry health checks

type MemoryCache ΒΆ

type MemoryCache struct {
	// contains filtered or unexported fields
}

MemoryCache implements Cache using in-memory storage

func NewMemoryCache ΒΆ

func NewMemoryCache(ttl time.Duration) *MemoryCache

NewMemoryCache creates a new memory cache

func (*MemoryCache) Clear ΒΆ

func (c *MemoryCache) Clear(ctx context.Context) error

Clear removes all entities from cache

func (*MemoryCache) Delete ΒΆ

func (c *MemoryCache) Delete(ctx context.Context, id string) error

Delete removes an entity from cache

func (*MemoryCache) Get ΒΆ

func (c *MemoryCache) Get(ctx context.Context, id string) (Entity, bool)

Get retrieves an entity from cache

func (*MemoryCache) Set ΒΆ

func (c *MemoryCache) Set(ctx context.Context, entity Entity) error

Set stores an entity in cache

func (*MemoryCache) Size ΒΆ

func (c *MemoryCache) Size() int

Size returns the number of cached entities

type Meta ΒΆ

type Meta struct {
	// Generic fields that can be used by any registry
	ID       string            `json:"id"`
	Name     string            `json:"name"`
	Active   bool              `json:"active"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

Meta represents generic metadata that can be associated with any entity

func Get ΒΆ

func Get(id string) Meta

type Metrics ΒΆ

type Metrics interface {
	IncrementRegistration()
	IncrementUnregistration()
	IncrementLookup()
	IncrementError()
	SetEntityCount(count int)
	SetActiveCount(count int)
	RecordLatency(operation string, duration time.Duration)
}

Metrics defines the interface for registry metrics

type Observer ΒΆ

type Observer interface {
	OnEntityRegistered(ctx context.Context, entity Entity)
	OnEntityUnregistered(ctx context.Context, id string)
	OnEntityUpdated(ctx context.Context, entity Entity)
	OnEntityActivated(ctx context.Context, id string)
	OnEntityDeactivated(ctx context.Context, id string)
}

Observer defines the interface for registry event observers

type Persistence ΒΆ

type Persistence interface {
	Save(ctx context.Context, entities []Entity) error
	Load(ctx context.Context) ([]Entity, error)
	Delete(ctx context.Context, id string) error
	Clear(ctx context.Context) error
}

Persistence defines the interface for registry persistence

type Provider ΒΆ

type Provider interface {
	// Core operations
	Register(ctx context.Context, entity Entity) error
	Get(ctx context.Context, id string) (Entity, error)
	Unregister(ctx context.Context, id string) error
	IsRegistered(ctx context.Context, id string) bool

	// Listing operations
	List(ctx context.Context) ([]Entity, error)
	ListActive(ctx context.Context) ([]Entity, error)
	ListByMetadata(ctx context.Context, key, value string) ([]Entity, error)

	// Counting operations
	Count(ctx context.Context) (int, error)
	CountActive(ctx context.Context) (int, error)

	// Metadata operations
	GetMetadata(ctx context.Context, id, key string) (string, error)
	SetMetadata(ctx context.Context, id, key, value string) error
	RemoveMetadata(ctx context.Context, id, key string) error

	// Lifecycle operations
	Activate(ctx context.Context, id string) error
	Deactivate(ctx context.Context, id string) error

	// Search operations
	Search(ctx context.Context, query string) ([]Entity, error)
	SearchByMetadata(ctx context.Context, metadata map[string]string) ([]Entity, error)
}

Provider defines the interface for registry implementations

func NewBasicRegistry ΒΆ

func NewBasicRegistry() Provider

NewBasicRegistry creates a basic registry with default settings

func NewCachedRegistry ΒΆ

func NewCachedRegistry(cacheSize int, cacheTTL time.Duration) Provider

NewCachedRegistry creates a registry with enhanced caching

func NewMonitoredRegistry ΒΆ

func NewMonitoredRegistry(name string) Provider

NewMonitoredRegistry creates a registry with metrics and monitoring

func NewPersistentRegistry ΒΆ

func NewPersistentRegistry(filePath string) (Provider, error)

NewPersistentRegistry creates a registry with file persistence

type RedisCache ΒΆ

type RedisCache struct {
	// contains filtered or unexported fields
}

RedisCache implements the Cache interface using Redis Note: This is a simplified version. The full implementation should be in registry_redis_cache.go

func NewRedisCache ΒΆ

func NewRedisCache(client *redis.Client, prefix string, ttl time.Duration) *RedisCache

NewRedisCache creates a new Redis cache for the registry

func (*RedisCache) Clear ΒΆ

func (c *RedisCache) Clear(ctx context.Context) error

Clear removes all cached entities with the prefix

func (*RedisCache) Delete ΒΆ

func (c *RedisCache) Delete(ctx context.Context, id string) error

Delete removes an entity from Redis cache

func (*RedisCache) Get ΒΆ

func (c *RedisCache) Get(ctx context.Context, id string) (Entity, bool)

Get retrieves an entity from Redis cache

func (*RedisCache) Set ΒΆ

func (c *RedisCache) Set(ctx context.Context, entity Entity) error

Set stores an entity in Redis cache

func (*RedisCache) Size ΒΆ

func (c *RedisCache) Size() int

Size returns the number of cache entries (approximate)

type Registry ΒΆ

type Registry struct {
	// contains filtered or unexported fields
}

Registry is a generic, thread-safe registry for managing any type of entity

func New ΒΆ

func New() *Registry

New creates a new empty registry

func (*Registry) Count ΒΆ

func (r *Registry) Count() int

Count returns the total number of registered entities

func (*Registry) Get ΒΆ

func (r *Registry) Get(id string) Meta

Get returns entity metadata for the given ID Returns empty Meta if the entity is not found

func (*Registry) GetMetadata ΒΆ

func (r *Registry) GetMetadata(id, key string) (string, bool)

GetMetadata returns a specific metadata value for an entity

func (*Registry) IsRegistered ΒΆ

func (r *Registry) IsRegistered(id string) bool

IsRegistered checks if an entity ID is registered

func (*Registry) ListActive ΒΆ

func (r *Registry) ListActive() []string

ListActive returns a list of all active entity IDs

func (*Registry) ListRegistered ΒΆ

func (r *Registry) ListRegistered() []string

ListRegistered returns a list of all registered entity IDs

func (*Registry) Register ΒΆ

func (r *Registry) Register(id string, meta Meta)

Register adds or updates an entity in the registry

func (*Registry) SetMetadata ΒΆ

func (r *Registry) SetMetadata(id, key, value string) bool

SetMetadata sets a specific metadata value for an entity

func (*Registry) Unregister ΒΆ

func (r *Registry) Unregister(id string) bool

Unregister removes an entity from the registry

type SimpleEventBus ΒΆ

type SimpleEventBus struct {
	// contains filtered or unexported fields
}

SimpleEventBus implements RegistryEventBus using in-memory event handling

func NewSimpleEventBus ΒΆ

func NewSimpleEventBus() *SimpleEventBus

NewSimpleEventBus creates a new simple event bus

func (*SimpleEventBus) Emit ΒΆ

func (b *SimpleEventBus) Emit(ctx context.Context, event Event) error

Publish publishes an event to all observers

func (*SimpleEventBus) Subscribe ΒΆ

func (b *SimpleEventBus) Subscribe(observer Observer) error

Subscribe adds an observer to the event bus

func (*SimpleEventBus) Unsubscribe ΒΆ

func (b *SimpleEventBus) Unsubscribe(observer Observer) error

Unsubscribe removes an observer from the event bus

type SimpleHealth ΒΆ

type SimpleHealth struct {
	// contains filtered or unexported fields
}

SimpleHealth implements Health with basic health checking

func NewSimpleHealth ΒΆ

func NewSimpleHealth() *SimpleHealth

NewSimpleHealth creates a new simple health checker

func (*SimpleHealth) ClearError ΒΆ

func (h *SimpleHealth) ClearError()

ClearError clears the last error

func (*SimpleHealth) GetHealthStatus ΒΆ

func (h *SimpleHealth) GetHealthStatus(ctx context.Context) map[string]interface{}

GetHealthStatus returns the health status

func (*SimpleHealth) GetLastError ΒΆ

func (h *SimpleHealth) GetLastError() error

GetLastError returns the last error

func (*SimpleHealth) IsHealthy ΒΆ

func (h *SimpleHealth) IsHealthy(ctx context.Context) bool

IsHealthy checks if the registry is healthy

func (*SimpleHealth) SetError ΒΆ

func (h *SimpleHealth) SetError(err error)

SetError sets the last error

type SimpleMetrics ΒΆ

type SimpleMetrics struct {
	// contains filtered or unexported fields
}

SimpleMetrics implements Metrics using simple counters

func NewSimpleMetrics ΒΆ

func NewSimpleMetrics() *SimpleMetrics

NewSimpleMetrics creates a new simple metrics collector

func (*SimpleMetrics) GetStats ΒΆ

func (m *SimpleMetrics) GetStats() map[string]interface{}

GetStats returns current metrics statistics

func (*SimpleMetrics) IncrementError ΒΆ

func (m *SimpleMetrics) IncrementError()

IncrementError increments the error counter

func (*SimpleMetrics) IncrementLookup ΒΆ

func (m *SimpleMetrics) IncrementLookup()

IncrementLookup increments the lookup counter

func (*SimpleMetrics) IncrementRegistration ΒΆ

func (m *SimpleMetrics) IncrementRegistration()

IncrementRegistration increments the registration counter

func (*SimpleMetrics) IncrementUnregistration ΒΆ

func (m *SimpleMetrics) IncrementUnregistration()

IncrementUnregistration increments the unregistration counter

func (*SimpleMetrics) RecordLatency ΒΆ

func (m *SimpleMetrics) RecordLatency(operation string, duration time.Duration)

RecordLatency records operation latency

func (*SimpleMetrics) SetActiveCount ΒΆ

func (m *SimpleMetrics) SetActiveCount(count int)

SetActiveCount sets the active entity count

func (*SimpleMetrics) SetEntityCount ΒΆ

func (m *SimpleMetrics) SetEntityCount(count int)

SetEntityCount sets the entity count

type SimpleValidator ΒΆ

type SimpleValidator struct {
	// contains filtered or unexported fields
}

SimpleValidator implements Validator with basic validation

func NewSimpleValidator ΒΆ

func NewSimpleValidator() *SimpleValidator

NewSimpleValidator creates a new simple validator

func (*SimpleValidator) Validate ΒΆ

func (v *SimpleValidator) Validate(ctx context.Context, entity Entity) error

Validate validates an entity

func (*SimpleValidator) ValidateMetadata ΒΆ

func (v *SimpleValidator) ValidateMetadata(ctx context.Context, metadata map[string]string) error

ValidateMetadata validates entity metadata

func (*SimpleValidator) WithForbiddenMetadata ΒΆ

func (v *SimpleValidator) WithForbiddenMetadata(fields []string) *SimpleValidator

WithForbiddenMetadata sets forbidden metadata fields

func (*SimpleValidator) WithRequiredMetadata ΒΆ

func (v *SimpleValidator) WithRequiredMetadata(fields []string) *SimpleValidator

WithRequiredMetadata sets required metadata fields

func (*SimpleValidator) WithValidator ΒΆ

func (v *SimpleValidator) WithValidator(
	field string,
	validator func(string) error,
) *SimpleValidator

WithValidator adds a custom validator for a metadata field

type Validator ΒΆ

type Validator interface {
	Validate(ctx context.Context, entity Entity) error
	ValidateMetadata(ctx context.Context, metadata map[string]string) error
}

Validator defines the interface for entity validation

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL