Documentation
ΒΆ
Overview ΒΆ
Example (Fourth) ΒΆ
Example_fourth demonstrates entity lifecycle management
registry := New()
// Create and register an entity
entity := NewBaseEntity("entity-1", "Test Entity")
entity.SetActive(true)
entity.SetMetadata("version", "1.0")
registry.Register("entity-1", entity)
fmt.Printf("Initial count: %d\n", registry.Count())
// Deactivate
entityFromRegistry := registry.Get("entity-1")
if be, ok := entityFromRegistry.(*BaseEntity); ok {
be.SetActive(false)
registry.Register("entity-1", be)
}
fmt.Printf("Active entities: %d\n", len(registry.ListActive()))
// Reactivate
entityFromRegistry = registry.Get("entity-1")
if be, ok := entityFromRegistry.(*BaseEntity); ok {
be.SetActive(true)
registry.Register("entity-1", be)
}
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
registry := New() // This avoids pollution from other tests/examples
// Use global registry functions
globalUser := NewBaseEntity("global-user", "Global User")
// Using setter methods (recommended)
globalUser.SetActive(true)
globalUser.SetMetadata("email", "user@example.com")
globalUser.SetMetadata("role", "admin")
registry.Register(globalUser.ID(), globalUser)
// Get from global registry
user := registry.Get("global-user")
if user != nil {
fmt.Printf("Global user: %s\n", user.Name())
}
// Check registration
fmt.Printf("Is registered: %t\n", registry.IsRegistered("global-user"))
// List all
all := registry.ListRegistered()
fmt.Printf("Global registry count: %d\n", len(all))
// Set metadata
registry.SetMetadata("global-user", "status", "active")
// Get metadata
status, found := registry.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()
// Create and register with metadata
product := NewBaseEntity("product-1", "Laptop")
// Using setter methods (recommended)
product.SetActive(true)
product.SetMetadata("category", "electronics")
product.SetMetadata("price", "99.99")
registry.Register("product-1", product)
// 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: 99.99 (found: true) In stock: true (found: true) Non-existent: (found: false)
Index ΒΆ
- Constants
- Variables
- func NewRedisClient(url string) (*redis.Client, error)
- type ActivationController
- type ActivationSetter
- type ActiveStatusChecker
- type BaseEntity
- func (e *BaseEntity) Active() bool
- func (e *BaseEntity) ClearMetadata()
- func (e *BaseEntity) CreatedAt() time.Time
- func (e *BaseEntity) DeleteMetadata(key string)
- func (e *BaseEntity) GetMetadataValue(key string) (string, bool)
- func (e *BaseEntity) HasMetadata(key string) bool
- func (e *BaseEntity) ID() string
- func (e *BaseEntity) MarshalJSON() ([]byte, error)
- func (e *BaseEntity) Metadata() map[string]string
- func (e *BaseEntity) Name() string
- func (e *BaseEntity) RemoveMetadata(key string)
- func (e *BaseEntity) SetActive(active bool)
- func (e *BaseEntity) SetID(id string) error
- func (e *BaseEntity) SetMetadata(key, value string)
- func (e *BaseEntity) SetMetadataMap(metadata map[string]string)
- func (e *BaseEntity) SetName(name string) error
- func (e *BaseEntity) UnmarshalJSON(data []byte) error
- func (e *BaseEntity) UpdatedAt() time.Time
- type Builder
- func (b *Builder) Build() Config
- func (b *Builder) BuildRegistry() (Provider, error)
- func (b *Builder) WithCache(size int, ttl time.Duration) *Builder
- func (b *Builder) WithDefaultTTL(ttl time.Duration) *Builder
- func (b *Builder) WithKeyPrefix(prefix string) *Builder
- func (b *Builder) WithMaxEntities(max int) *Builder
- func (b *Builder) WithName(name string) *Builder
- func (b *Builder) WithPersistence(path string, interval time.Duration) *Builder
- func (b *Builder) WithRedis(url string) *Builder
- func (b *Builder) WithRedisAdvanced(url string, prefix string, poolSize int, minIdleConns int, maxRetries int, ...) *Builder
- func (b *Builder) WithValidation(required, forbidden []string) *Builder
- type Cache
- type Config
- type Enhanced
- func (r *Enhanced) Activate(ctx context.Context, id string) error
- func (r *Enhanced) AddObserver(observer Observer)
- func (r *Enhanced) Count(ctx context.Context) (int, error)
- func (r *Enhanced) CountActive(ctx context.Context) (int, error)
- func (r *Enhanced) Deactivate(ctx context.Context, id string) error
- func (r *Enhanced) Get(ctx context.Context, id string) (Entity, error)
- func (r *Enhanced) GetMetadata(ctx context.Context, id, key string) (string, error)
- func (r *Enhanced) IsRegistered(ctx context.Context, id string) bool
- func (r *Enhanced) List(ctx context.Context) ([]Entity, error)
- func (r *Enhanced) ListActive(ctx context.Context) ([]Entity, error)
- func (r *Enhanced) ListByMetadata(ctx context.Context, key, value string) ([]Entity, error)
- func (r *Enhanced) Register(ctx context.Context, entity Entity) error
- func (r *Enhanced) RemoveMetadata(ctx context.Context, id, key string) error
- func (r *Enhanced) RemoveObserver(observer Observer)
- func (r *Enhanced) Search(ctx context.Context, query string) ([]Entity, error)
- func (r *Enhanced) SearchByMetadata(ctx context.Context, metadata map[string]string) ([]Entity, error)
- func (r *Enhanced) SetMetadata(ctx context.Context, id, key, value string) error
- func (r *Enhanced) Unregister(ctx context.Context, id string) error
- func (r *Enhanced) WithCache(cache Cache) *Enhanced
- func (r *Enhanced) WithEventBus(eventBus EventBus) *Enhanced
- func (r *Enhanced) WithHealth(health Health) *Enhanced
- func (r *Enhanced) WithMetrics(metrics Metrics) *Enhanced
- func (r *Enhanced) WithPersistence(persistence Persistence) *Enhanced
- func (r *Enhanced) WithValidator(validator Validator) *Enhanced
- type EnhancedRegistrydeprecated
- type Entity
- type EntityCore
- type EntityFactory
- type EntityFull
- type EntityLifecycle
- type EntityValidator
- type Event
- type EventBus
- type Factory
- type FactoryImpl
- func (f *FactoryImpl) Create(ctx context.Context, config Config) (Provider, error)
- func (f *FactoryImpl) CreateForDevelopment(ctx context.Context, name string) (Provider, error)
- func (f *FactoryImpl) CreateForProduction(ctx context.Context, name string, persistencePath string) (Provider, error)
- func (f *FactoryImpl) CreateForTesting(ctx context.Context) (Provider, error)
- func (f *FactoryImpl) CreateFullFeatured(ctx context.Context, config Config) (Provider, error)
- func (f *FactoryImpl) CreateWithCache(ctx context.Context, config Config, cache Cache) (Provider, error)
- func (f *FactoryImpl) CreateWithMetrics(ctx context.Context, config Config, metrics Metrics) (Provider, error)
- func (f *FactoryImpl) CreateWithPersistence(ctx context.Context, config Config, persistence Persistence) (Provider, error)
- func (f *FactoryImpl) CreateWithRedisCache(ctx context.Context, config Config, redisURL string) (Provider, error)
- type FilePersistence
- type Health
- type IDSetter
- type Identifier
- type Identity
- type MemoryCache
- type MetadataClearer
- type MetadataController
- type MetadataReader
- type MetadataRemover
- type MetadataWriter
- type Metrics
- type NameSetter
- type Nameable
- type Named
- type Observer
- type Persistence
- type Provider
- type RedisCache
- type Registry
- func (r *Registry) Count() int
- func (r *Registry) Get(id string) Entity
- func (r *Registry) GetMetadata(id, key string) (string, bool)
- func (r *Registry) IsRegistered(id string) bool
- func (r *Registry) ListActive() []string
- func (r *Registry) ListRegistered() []string
- func (r *Registry) Register(id string, entity Entity)
- func (r *Registry) RemoveMetadata(id, key string) bool
- func (r *Registry) SetMetadata(id, key, value string) bool
- func (r *Registry) Unregister(id string) bool
- type RegistryCachedeprecated
- type RegistryConfigdeprecated
- type RegistryEntitydeprecated
- type RegistryEventdeprecated
- type RegistryEventBusdeprecated
- type RegistryFactorydeprecated
- type RegistryFactoryImpldeprecated
- type RegistryHealthdeprecated
- type RegistryMetricsdeprecated
- type RegistryObserverdeprecated
- type RegistryPersistencedeprecated
- type RegistryProviderdeprecated
- type RegistryValidatordeprecated
- type SimpleEventBus
- type SimpleHealth
- type SimpleMetrics
- func (m *SimpleMetrics) GetStats() map[string]interface{}
- func (m *SimpleMetrics) IncrementError()
- func (m *SimpleMetrics) IncrementLookup()
- func (m *SimpleMetrics) IncrementRegistration()
- func (m *SimpleMetrics) IncrementUnregistration()
- func (m *SimpleMetrics) RecordLatency(operation string, duration time.Duration)
- func (m *SimpleMetrics) SetActiveCount(count int)
- func (m *SimpleMetrics) SetEntityCount(count int)
- type SimpleValidator
- func (v *SimpleValidator) Validate(ctx context.Context, entity Entity) error
- func (v *SimpleValidator) ValidateMetadata(ctx context.Context, metadata map[string]string) error
- func (v *SimpleValidator) WithForbiddenMetadata(fields []string) *SimpleValidator
- func (v *SimpleValidator) WithRequiredMetadata(fields []string) *SimpleValidator
- func (v *SimpleValidator) WithValidator(field string, validator func(string) error) *SimpleValidator
- type Timestamped
- type Validator
Examples ΒΆ
Constants ΒΆ
const ( EventEntityRegistered = "entity_registered" EventEntityUnregistered = "entity_unregistered" EventEntityUpdated = "entity_updated" EventEntityActivated = "entity_activated" EventEntityDeactivated = "entity_deactivated" )
EventType constants
Variables ΒΆ
var ErrNotFound = errors.New("entity not found")
Functions ΒΆ
Types ΒΆ
type ActivationController ΒΆ added in v1.3.0
type ActivationController interface {
ActiveStatusChecker
ActivationSetter
}
type ActivationSetter ΒΆ added in v1.3.0
type ActivationSetter interface {
SetActive(active bool)
}
type ActiveStatusChecker ΒΆ added in v1.3.0
type ActiveStatusChecker interface {
Active() bool
}
ActiveStatusChecker defines the interface for checking if an entity is active
type BaseEntity ΒΆ
type BaseEntity struct {
// Deprecated: Use ID() and SetID() methods instead
BEId string
// Deprecated: Use Name() and SetName() methods instead
BEName string
// Deprecated: Use Active() and SetActive() methods instead
BEActive bool
// Deprecated: Use Metadata() and related methods instead
BEMetadata map[string]string
// Deprecated: Use CreatedAt() and UpdatedAt() methods instead
BECreatedAt time.Time
// Deprecated: Use CreatedAt() and UpdatedAt() methods instead
BEUpdatedAt time.Time
// contains filtered or unexported fields
}
/ BaseEntity provides a thread-safe default implementation of core entity interfaces. It serves as a foundation for domain-specific entities by providing common functionality including:
- Unique identifier management (ID)
- Naming and activation state
- Key-value metadata storage
- Creation and modification timestamps
- Concurrent access safety
BaseEntity implements the following interfaces:
- Identifiable: For ID management
- Named: For name-related operations
- ActivationController: For activation state management
- MetadataController: For metadata operations
- Timestamped: For creation/update timestamps
- Entity: Composite interface for backward compatibility
Example usage:
type User struct {
registry.BaseEntity
Email string
Password string `json:"-"`
}
All exported methods are safe for concurrent access. The struct uses a read-write mutex to protect all internal state. When embedding BaseEntity, ensure proper initialization of the embedded fields.
func MustNewBaseEntity ΒΆ added in v1.3.0
func MustNewBaseEntity(id, name string) *BaseEntity
Use only when you're certain the inputs are valid.
func NewBaseEntity ΒΆ
func NewBaseEntity(id, name string) *BaseEntity
NewBaseEntity creates a new BaseEntity with the given id and name. The entity will be active by default and have the creation time set to now. Returns an error if id or name is empty.
This function returns a concrete *BaseEntity type. If you need the Entity interface, the return value can be assigned to an Entity variable.
func (*BaseEntity) Active ΒΆ
func (e *BaseEntity) Active() bool
Active returns whether the entity is active. It's safe for concurrent access.
func (*BaseEntity) ClearMetadata ΒΆ added in v1.3.0
func (e *BaseEntity) ClearMetadata()
ClearMetadata removes all metadata from the entity. It's safe for concurrent access.
func (*BaseEntity) CreatedAt ΒΆ
func (e *BaseEntity) CreatedAt() time.Time
CreatedAt returns when the entity was created. It's safe for concurrent access.
func (*BaseEntity) DeleteMetadata ΒΆ added in v1.3.0
func (e *BaseEntity) DeleteMetadata(key string)
DeleteMetadata removes a metadata key from the entity. It's safe for concurrent access.
func (*BaseEntity) GetMetadataValue ΒΆ added in v1.3.0
func (e *BaseEntity) GetMetadataValue(key string) (string, bool)
GetMetadataValue returns the value for a metadata key and whether it exists. This method is more efficient than Metadata() when you only need one value.
func (*BaseEntity) HasMetadata ΒΆ added in v1.3.0
func (e *BaseEntity) HasMetadata(key string) bool
HasMetadata checks if the entity has a specific metadata key. This method is safe for concurrent access.
func (*BaseEntity) ID ΒΆ
func (e *BaseEntity) ID() string
ID returns the entity's ID. It's safe for concurrent access.
func (*BaseEntity) MarshalJSON ΒΆ added in v1.3.0
func (e *BaseEntity) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface. It provides custom JSON marshaling for BaseEntity. This method is safe for concurrent access.
func (*BaseEntity) Metadata ΒΆ
func (e *BaseEntity) Metadata() map[string]string
Metadata returns a copy of the entity's metadata. It's safe for concurrent access.
func (*BaseEntity) Name ΒΆ
func (e *BaseEntity) Name() string
Name returns the entity's name. It's safe for concurrent access.
func (*BaseEntity) RemoveMetadata ΒΆ added in v1.3.0
func (e *BaseEntity) RemoveMetadata(key string)
RemoveMetadata removes a metadata key and updates the updated timestamp. If the key doesn't exist, this is a no-op. This method is safe for concurrent access.
func (*BaseEntity) SetActive ΒΆ added in v1.3.0
func (e *BaseEntity) SetActive(active bool)
SetActive sets the active state of the entity. It's safe for concurrent access.
func (*BaseEntity) SetID ΒΆ added in v1.3.0
func (e *BaseEntity) SetID(id string) error
SetID sets the ID of the entity. It's safe for concurrent access.
func (*BaseEntity) SetMetadata ΒΆ added in v1.3.0
func (e *BaseEntity) SetMetadata(key, value string)
SetMetadata sets a metadata key-value pair. It's safe for concurrent access.
func (*BaseEntity) SetMetadataMap ΒΆ added in v1.3.0
func (e *BaseEntity) SetMetadataMap(metadata map[string]string)
SetMetadataMap sets multiple metadata key-value pairs at once and updates the updated timestamp. This is more efficient than calling SetMetadata multiple times as it only acquires the lock once. This method is safe for concurrent access.
func (*BaseEntity) SetName ΒΆ added in v1.3.0
func (e *BaseEntity) SetName(name string) error
SetName sets the name of the entity. It's safe for concurrent access.
func (*BaseEntity) UnmarshalJSON ΒΆ added in v1.3.0
func (e *BaseEntity) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface. It provides custom JSON unmarshaling for BaseEntity. This method is safe for concurrent access.
func (*BaseEntity) UpdatedAt ΒΆ
func (e *BaseEntity) UpdatedAt() time.Time
UpdatedAt returns when the entity was last updated. It's safe for concurrent access.
type Builder ΒΆ
type Builder struct {
// contains filtered or unexported fields
}
Builder provides a fluent interface for building registry configurations
func NewRegistryBuilder
deprecated
added in
v1.3.0
func NewRegistryBuilder() *Builder
Deprecated: Use NewBuilder instead NewRegistryBuilder is the old name for NewBuilder
func (*Builder) BuildRegistry ΒΆ
BuildRegistry creates a registry with the built configuration
func (*Builder) WithDefaultTTL ΒΆ
WithDefaultTTL sets the default TTL for entities
func (*Builder) WithKeyPrefix ΒΆ
WithKeyPrefix sets the Redis key prefix for the registry
func (*Builder) WithMaxEntities ΒΆ
WithMaxEntities sets the maximum number of entities
func (*Builder) WithPersistence ΒΆ
WithPersistence enables persistence with the given path
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 ΒΆ
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 ΒΆ
NewEnhanced creates a new enhanced registry
func NewEnhancedRegistry
deprecated
added in
v1.3.0
func (*Enhanced) AddObserver ΒΆ
AddObserver adds an observer to the registry
func (*Enhanced) CountActive ΒΆ
CountActive returns the number of active entities
func (*Enhanced) Deactivate ΒΆ
Deactivate deactivates an entity
func (*Enhanced) GetMetadata ΒΆ
GetMetadata retrieves specific metadata for an entity
func (*Enhanced) IsRegistered ΒΆ
IsRegistered checks if an entity is registered
func (*Enhanced) ListActive ΒΆ
ListActive returns all active entities
func (*Enhanced) ListByMetadata ΒΆ
ListByMetadata returns entities with specific metadata
func (*Enhanced) RemoveMetadata ΒΆ
RemoveMetadata removes specific metadata from an entity
func (*Enhanced) RemoveObserver ΒΆ
RemoveObserver removes an observer from the registry
func (*Enhanced) SearchByMetadata ΒΆ
func (r *Enhanced) SearchByMetadata( ctx context.Context, metadata map[string]string, ) ([]Entity, error)
SearchByMetadata searches entities by metadata
func (*Enhanced) SetMetadata ΒΆ
SetMetadata sets specific metadata for an entity
func (*Enhanced) Unregister ΒΆ
Unregister removes an entity from the registry
func (*Enhanced) WithEventBus ΒΆ
WithEventBus sets the event bus for the registry
func (*Enhanced) WithHealth ΒΆ
WithHealth sets the health checker for the registry
func (*Enhanced) WithMetrics ΒΆ
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 ΒΆ
WithValidator sets the validator for the registry
type EnhancedRegistry
deprecated
added in
v1.3.0
type EnhancedRegistry = Enhanced
Deprecated: Use Enhanced instead NewEnhancedRegistry was renamed to NewEnhanced for brevity
type Entity ΒΆ
type Entity = EntityCore
Entity is the main interface that all registry entities must implement It's a composition of smaller, focused interfaces Deprecated: Use EntityCore for new code
type EntityCore ΒΆ added in v1.3.0
type EntityCore interface {
Identity
Nameable
ActivationController
MetadataController
Timestamped
}
type EntityFactory ΒΆ added in v1.3.0
type EntityFactory interface {
NewEntity(id, name string) (EntityCore, error)
}
EntityFactory creates new entity instances
type EntityFull ΒΆ added in v1.3.0
type EntityFull interface {
EntityCore
EntityValidator
EntityLifecycle
}
EntityFull combines all entity-related interfaces
type EntityLifecycle ΒΆ added in v1.3.0
type EntityLifecycle interface {
BeforeCreate() error
AfterCreate() error
BeforeUpdate() error
AfterUpdate() error
BeforeDelete() error
AfterDelete() error
}
EntityLifecycle defines hooks for entity lifecycle events
type EntityValidator ΒΆ added in v1.3.0
type EntityValidator interface {
Validate() error
}
EntityValidator validates entity state
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]any `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 NewFactory ΒΆ added in v1.3.0
func NewFactory() Factory
NewFactory creates a new registry factory
func NewRegistryFactory
deprecated
func NewRegistryFactory() Factory
Deprecated: Use NewFactory instead NewRegistryFactory is the old name for NewFactory
type FactoryImpl ΒΆ
type FactoryImpl struct{}
FactoryImpl implements RegistryFactory
func (*FactoryImpl) CreateForDevelopment ΒΆ
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 ΒΆ
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
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 Identifier ΒΆ added in v1.3.0
type Identifier interface {
ID() string
}
Basic interfaces (single-method)
type Identity ΒΆ added in v1.3.0
type Identity interface {
Identifier
IDSetter
}
Composite interfaces
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) 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 MetadataClearer ΒΆ added in v1.3.0
type MetadataClearer interface {
ClearMetadata()
}
type MetadataController ΒΆ added in v1.3.0
type MetadataController interface {
MetadataReader
MetadataWriter
MetadataRemover
MetadataClearer
}
type MetadataReader ΒΆ added in v1.3.0
type MetadataRemover ΒΆ added in v1.3.0
type MetadataRemover interface {
RemoveMetadata(key string)
}
type MetadataWriter ΒΆ added in v1.3.0
type MetadataWriter interface {
SetMetadata(key, value string)
}
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 NameSetter ΒΆ added in v1.3.0
type Nameable ΒΆ added in v1.3.0
type Nameable interface {
Named
NameSetter
}
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 ΒΆ
NewCachedRegistry creates a registry with enhanced caching
func NewMonitoredRegistry ΒΆ
NewMonitoredRegistry creates a registry with metrics and monitoring
func NewPersistentRegistry ΒΆ
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 ΒΆ
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) 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 thread-safe registry for managing entities that implement the Entity interface
Example ΒΆ
ExampleRegistry demonstrates basic registry usage
// Create a new registry instance
registry := New()
// Create entities using NewBaseEntity and set properties using methods
user1 := NewBaseEntity("user-1", "John Doe")
user1.SetActive(true)
user1.SetMetadata("email", "john@example.com")
user1.SetMetadata("role", "admin")
user2 := NewBaseEntity("user-2", "Jane Smith")
user2.SetActive(true)
user2.SetMetadata("email", "jane@example.com")
user2.SetMetadata("role", "user")
// Register entities
registry.Register(user1.ID(), user1)
registry.Register(user2.ID(), user2)
// Get an entity
user := registry.Get("user-1")
if user != nil {
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
func (*Registry) Get ΒΆ
Get returns the entity for the given ID Returns nil if the entity is not found
func (*Registry) GetMetadata ΒΆ
GetMetadata returns a specific metadata value for an entity
func (*Registry) IsRegistered ΒΆ
IsRegistered checks if an entity ID is registered
func (*Registry) ListActive ΒΆ
ListActive returns a list of all active entity IDs
func (*Registry) ListRegistered ΒΆ
ListRegistered returns a list of all registered entity IDs
func (*Registry) RemoveMetadata ΒΆ added in v1.3.0
RemoveMetadata removes a specific metadata key from an entity
func (*Registry) SetMetadata ΒΆ
SetMetadata sets a specific metadata value for an entity
func (*Registry) Unregister ΒΆ
Unregister removes an entity from the registry
type RegistryCache
deprecated
added in
v1.3.0
type RegistryCache = Cache
Deprecated: Use Cache instead RegistryCache is the old name for the Cache interface
type RegistryConfig
deprecated
added in
v1.3.0
type RegistryConfig = Config
Deprecated: Use Config instead RegistryConfig is the old name for the Config struct
type RegistryEntity
deprecated
added in
v1.3.0
type RegistryEntity = Entity
Deprecated: Use Entity instead RegistryEntity is the old name for the Entity interface
type RegistryEvent
deprecated
added in
v1.3.0
type RegistryEvent = Event
Deprecated: Use Event instead RegistryEvent is the old name for the Event struct
type RegistryEventBus
deprecated
added in
v1.3.0
type RegistryEventBus = EventBus
Deprecated: Use EventBus instead RegistryEventBus is the old name for the EventBus interface
type RegistryFactory
deprecated
added in
v1.3.0
type RegistryFactory = Factory
Deprecated: Use Factory instead RegistryFactory is the old name for the Factory interface
type RegistryFactoryImpl
deprecated
added in
v1.3.0
type RegistryFactoryImpl = FactoryImpl
Deprecated: Use FactoryImpl instead RegistryFactoryImpl is the old name for the FactoryImpl struct
type RegistryHealth
deprecated
added in
v1.3.0
type RegistryHealth = Health
Deprecated: Use Health instead RegistryHealth is the old name for the Health interface
type RegistryMetrics
deprecated
added in
v1.3.0
type RegistryMetrics = Metrics
Deprecated: Use Metrics instead RegistryMetrics is the old name for the Metrics interface
type RegistryObserver
deprecated
added in
v1.3.0
type RegistryObserver = Observer
Deprecated: Use Observer instead RegistryObserver is the old name for the Observer interface
type RegistryPersistence
deprecated
added in
v1.3.0
type RegistryPersistence = Persistence
Deprecated: Use Persistence instead RegistryPersistence is the old name for the Persistence interface
type RegistryProvider
deprecated
added in
v1.3.0
type RegistryProvider = Provider
Deprecated: Use Provider instead RegistryProvider is the old name for the Provider interface
type RegistryValidator
deprecated
added in
v1.3.0
type RegistryValidator = Validator
Deprecated: Use Validator instead RegistryValidator is the old name for the Validator interface
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 ΒΆ
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