Documentation
¶
Index ¶
- func DumpCacheToFile(cache interface{}, filename string) error
- func DumpForestToFile(m *MemoryMatcherEngine, filename string) error
- func GenerateDefaultNodeID() string
- func SetLogger(log *slog.Logger)
- type Broker
- type CacheEntry
- type DatabasePersistence
- func (dp *DatabasePersistence) Health(ctx context.Context) error
- func (dp *DatabasePersistence) LoadDimensionConfigs(ctx context.Context) ([]*DimensionConfig, error)
- func (dp *DatabasePersistence) LoadDimensionConfigsByTenant(ctx context.Context, tenantID, applicationID string) ([]*DimensionConfig, error)
- func (dp *DatabasePersistence) LoadRules(ctx context.Context) ([]*Rule, error)
- func (dp *DatabasePersistence) LoadRulesByTenant(ctx context.Context, tenantID, applicationID string) ([]*Rule, error)
- func (dp *DatabasePersistence) SaveDimensionConfigs(ctx context.Context, configs []*DimensionConfig) error
- func (dp *DatabasePersistence) SaveRules(ctx context.Context, rules []*Rule) error
- type DimensionConfig
- type DimensionConfigs
- func (dc *DimensionConfigs) Add(config *DimensionConfig)
- func (dc *DimensionConfigs) Clone(dcs []*DimensionConfig) *DimensionConfigs
- func (dc *DimensionConfigs) CloneDimension(name string) *DimensionConfig
- func (dc *DimensionConfigs) CloneSorted() []*DimensionConfig
- func (dc *DimensionConfigs) Count() int
- func (dc *DimensionConfigs) Exist(name string) bool
- func (dc *DimensionConfigs) Get(i int) (string, bool)
- func (dc *DimensionConfigs) GetSortedNames() []string
- func (dc *DimensionConfigs) GetWeight(name string, mt MatchType) (float64, bool)
- func (dc *DimensionConfigs) IsRequired(name string) bool
- func (dc *DimensionConfigs) LoadBulk(configs []*DimensionConfig)
- func (dc *DimensionConfigs) Remove(dimensionName string) bool
- func (dc *DimensionConfigs) SetSorter(sorter func([]*DimensionConfig))
- type DimensionEvent
- type DimensionValue
- type Event
- type EventType
- type ForestIndex
- type JSONPersistence
- func (jp *JSONPersistence) Health(ctx context.Context) error
- func (jp *JSONPersistence) LoadDimensionConfigs(ctx context.Context) ([]*DimensionConfig, error)
- func (jp *JSONPersistence) LoadDimensionConfigsByTenant(ctx context.Context, tenantID, applicationID string) ([]*DimensionConfig, error)
- func (jp *JSONPersistence) LoadRules(ctx context.Context) ([]*Rule, error)
- func (jp *JSONPersistence) LoadRulesByTenant(ctx context.Context, tenantID, applicationID string) ([]*Rule, error)
- func (jp *JSONPersistence) SaveDimensionConfigs(ctx context.Context, configs []*DimensionConfig) error
- func (jp *JSONPersistence) SaveRules(ctx context.Context, rules []*Rule) error
- type KafkaEventSubscriber
- type LatestEvent
- type MatchBranch
- type MatchResult
- type MatchType
- type MatcherEngine
- func (me *MatcherEngine) AddAnyRule(id string, dimensionNames []string, manualWeight float64) error
- func (me *MatcherEngine) AddDimension(config *DimensionConfig) error
- func (me *MatcherEngine) AddRule(rule *Rule) error
- func (me *MatcherEngine) AddSimpleRule(id string, dimensions map[string]string, manualWeight *float64) error
- func (me *MatcherEngine) AutoSave(interval time.Duration) chan<- bool
- func (me *MatcherEngine) BatchAddRules(rules []*Rule) error
- func (me *MatcherEngine) ClearCache()
- func (me *MatcherEngine) Close() error
- func (me *MatcherEngine) DeleteRule(ruleID string) error
- func (me *MatcherEngine) FindAllMatches(query *QueryRule) ([]*MatchResult, error)
- func (me *MatcherEngine) FindAllMatchesInBatch(query ...*QueryRule) ([][]*MatchResult, error)
- func (me *MatcherEngine) FindBestMatch(query *QueryRule) (*MatchResult, error)
- func (me *MatcherEngine) FindBestMatchInBatch(queries ...*QueryRule) ([]*MatchResult, error)
- func (me *MatcherEngine) GetCacheStats() map[string]interface{}
- func (me *MatcherEngine) GetDimensionConfigs() *DimensionConfigs
- func (me *MatcherEngine) GetForestStats() map[string]interface{}
- func (me *MatcherEngine) GetRule(ruleID string) (*Rule, error)
- func (me *MatcherEngine) GetStats() *MatcherStats
- func (me *MatcherEngine) Health() error
- func (me *MatcherEngine) ListDimensions() ([]*DimensionConfig, error)
- func (me *MatcherEngine) ListRules(offset, limit int) ([]*Rule, error)
- func (me *MatcherEngine) LoadDimensions(configs []*DimensionConfig)
- func (me *MatcherEngine) Rebuild() error
- func (me *MatcherEngine) Save() error
- func (me *MatcherEngine) SaveToPersistence() error
- func (me *MatcherEngine) SetAllowDuplicateWeights(allow bool)
- func (me *MatcherEngine) UpdateRule(rule *Rule) error
- func (me *MatcherEngine) UpdateRuleMetadata(ruleID string, metadata map[string]string) error
- func (me *MatcherEngine) UpdateRuleStatus(ruleID string, status RuleStatus) error
- func (me *MatcherEngine) ValidateRule(rule *Rule) error
- type MatcherStats
- type MemoryMatcherEngine
- func (m *MemoryMatcherEngine) AddDimension(config *DimensionConfig) error
- func (m *MemoryMatcherEngine) AddRule(rule *Rule) error
- func (m *MemoryMatcherEngine) Close() error
- func (m *MemoryMatcherEngine) DeleteRule(ruleID string) error
- func (m *MemoryMatcherEngine) FindAllMatches(query *QueryRule) ([]*MatchResult, error)
- func (m *MemoryMatcherEngine) FindAllMatchesInBatch(queries []*QueryRule) ([][]*MatchResult, error)
- func (m *MemoryMatcherEngine) FindBestMatch(query *QueryRule) (*MatchResult, error)
- func (m *MemoryMatcherEngine) FindBestMatchInBatch(queries []*QueryRule) ([]*MatchResult, error)
- func (m *MemoryMatcherEngine) GetDimensionConfigs() *DimensionConfigs
- func (m *MemoryMatcherEngine) GetRule(ruleID string) (*Rule, error)
- func (m *MemoryMatcherEngine) GetStats() *MatcherStats
- func (m *MemoryMatcherEngine) Health() error
- func (m *MemoryMatcherEngine) ListDimensions() ([]*DimensionConfig, error)
- func (m *MemoryMatcherEngine) ListRules(offset, limit int) ([]*Rule, error)
- func (m *MemoryMatcherEngine) LoadDimensions(configs []*DimensionConfig)
- func (m *MemoryMatcherEngine) Rebuild() error
- func (m *MemoryMatcherEngine) SaveToPersistence() error
- func (m *MemoryMatcherEngine) SetAllowDuplicateWeights(allow bool)
- func (m *MemoryMatcherEngine) UpdateRule(rule *Rule) error
- type MockEventSubscriber
- func (mes *MockEventSubscriber) Close() error
- func (mes *MockEventSubscriber) Health(ctx context.Context) error
- func (mes *MockEventSubscriber) Publish(ctx context.Context, event *Event) error
- func (mes *MockEventSubscriber) PublishEvent(event *Event)
- func (mes *MockEventSubscriber) Subscribe(ctx context.Context, events chan<- *Event) error
- type MultiLevelCache
- type PersistenceInterface
- type QueryCache
- func (qc *QueryCache) CleanupExpired() int
- func (qc *QueryCache) Clear()
- func (qc *QueryCache) Get(query *QueryRule) *MatchResult
- func (qc *QueryCache) Set(query *QueryRule, result *MatchResult)
- func (qc *QueryCache) SetWithTTL(query *QueryRule, result *MatchResult, ttl time.Duration)
- func (qc *QueryCache) Size() int
- func (qc *QueryCache) StartCleanupWorker(interval time.Duration) chan<- bool
- func (qc *QueryCache) Stats() map[string]interface{}
- type QueryRule
- func CreateQuery(values map[string]string) *QueryRule
- func CreateQueryWithAllRules(values map[string]string) *QueryRule
- func CreateQueryWithAllRulesAndDynamicConfigs(values map[string]string, dynamicConfigs *DimensionConfigs) *QueryRule
- func CreateQueryWithAllRulesAndExcluded(values map[string]string, excludeRuleIDs []string) *QueryRule
- func CreateQueryWithAllRulesAndTenant(tenantID, applicationID string, values map[string]string) *QueryRule
- func CreateQueryWithAllRulesTenantAndDynamicConfigs(tenantID, applicationID string, values map[string]string, ...) *QueryRule
- func CreateQueryWithAllRulesTenantAndExcluded(tenantID, applicationID string, values map[string]string, ...) *QueryRule
- func CreateQueryWithDynamicConfigs(values map[string]string, dynamicConfigs *DimensionConfigs) *QueryRule
- func CreateQueryWithExcludedRules(values map[string]string, excludeRuleIDs []string) *QueryRule
- func CreateQueryWithTenant(tenantID, applicationID string, values map[string]string) *QueryRule
- func CreateQueryWithTenantAndDynamicConfigs(tenantID, applicationID string, values map[string]string, ...) *QueryRule
- func CreateQueryWithTenantAndExcluded(tenantID, applicationID string, values map[string]string, ...) *QueryRule
- type RedisBroker
- type RedisCASBroker
- func NewClusterRedisCASBroker(addrs []string, password, nodeID string) (*RedisCASBroker, error)
- func NewRedisCASBroker(config RedisCASConfig) (*RedisCASBroker, error)
- func NewSentinelRedisCASBroker(sentinelAddrs []string, masterName, password, nodeID string) (*RedisCASBroker, error)
- func NewSingleNodeRedisCASBroker(addr, password, nodeID string) (*RedisCASBroker, error)
- func (r *RedisCASBroker) Close() error
- func (r *RedisCASBroker) GetLastTimestamp() int64
- func (r *RedisCASBroker) GetLatestEvent(ctx context.Context) (*LatestEvent, error)
- func (r *RedisCASBroker) Health(ctx context.Context) error
- func (r *RedisCASBroker) Publish(ctx context.Context, event *Event) error
- func (r *RedisCASBroker) Subscribe(ctx context.Context, events chan<- *Event) error
- func (r *RedisCASBroker) WaitForTimestamp(ctx context.Context, targetTimestamp int64, timeout time.Duration) error
- type RedisCASConfig
- type RedisClientInterface
- type RedisEventBrokerConfig
- type Rule
- func (r *Rule) CalculateTotalWeight(dimensionConfigs *DimensionConfigs) float64
- func (r *Rule) Clone() *Rule
- func (r *Rule) CloneAndComplete(dimensions []string) *Rule
- func (r *Rule) GetDimensionMatchType(dimensionName string) MatchType
- func (r *Rule) GetDimensionValue(dimensionName string) *DimensionValue
- func (r *Rule) GetTenantContext() (tenantID, applicationID string)
- func (r *Rule) HasDimension(dimensionName string) bool
- func (r *Rule) MatchesTenantContext(tenantID, applicationID string) bool
- type RuleBuilder
- func (rb *RuleBuilder) Application(applicationID string) *RuleBuilder
- func (rb *RuleBuilder) Build() *Rule
- func (rb *RuleBuilder) Dimension(name, value string, matchType MatchType) *RuleBuilder
- func (rb *RuleBuilder) ManualWeight(weight float64) *RuleBuilder
- func (rb *RuleBuilder) Metadata(key, value string) *RuleBuilder
- func (rb *RuleBuilder) Status(status RuleStatus) *RuleBuilder
- func (rb *RuleBuilder) Tenant(tenantID string) *RuleBuilder
- type RuleEvent
- type RuleForest
- func (rf *RuleForest) AddRule(rule *Rule) (*Rule, error)
- func (rf *RuleForest) FindCandidateRules(queryValues interface{}) []RuleWithWeight
- func (rf *RuleForest) GetStats() map[string]interface{}
- func (rf *RuleForest) InitializeDimension(dimensionName string)
- func (rf *RuleForest) RemoveRule(rule *Rule)
- func (rf *RuleForest) ReplaceRule(oldRule, newRule *Rule) error
- type RuleStatus
- type RuleWithWeight
- type SharedNode
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DumpCacheToFile ¶
DumpCacheToFile dumps the cache as key-value pairs to a file
func DumpForestToFile ¶
func DumpForestToFile(m *MemoryMatcherEngine, filename string) error
DumpForestToFile dumps the forest in concise graph format to a file
func GenerateDefaultNodeID ¶
func GenerateDefaultNodeID() string
GenerateDefaultNodeID generates a default node ID based on hostname and random suffix
Types ¶
type Broker ¶
type Broker interface {
// Publish publishes an event to the message queue
Publish(ctx context.Context, event *Event) error
// Subscribe starts listening for events and sends them to the provided channel
Subscribe(ctx context.Context, events chan<- *Event) error
// Health check
Health(ctx context.Context) error
// Close closes the broker (both publisher and subscriber)
Close() error
}
Broker defines the unified interface for both event publishing and subscription
type CacheEntry ¶
type CacheEntry struct {
Key string `json:"key"`
Result *MatchResult `json:"result"`
Timestamp time.Time `json:"timestamp"`
TTL time.Duration `json:"ttl"`
}
CacheEntry represents a cached query result
func (*CacheEntry) IsExpired ¶
func (ce *CacheEntry) IsExpired() bool
IsExpired checks if the cache entry has expired
type DatabasePersistence ¶
type DatabasePersistence struct {
// contains filtered or unexported fields
}
DatabasePersistence implements PersistenceInterface using a SQL database This is a placeholder - you would use your preferred database driver
func NewDatabasePersistence ¶
func NewDatabasePersistence(connectionString string) *DatabasePersistence
NewDatabasePersistence creates a new database persistence layer
func (*DatabasePersistence) Health ¶
func (dp *DatabasePersistence) Health(ctx context.Context) error
Health checks if the database connection is healthy
func (*DatabasePersistence) LoadDimensionConfigs ¶
func (dp *DatabasePersistence) LoadDimensionConfigs(ctx context.Context) ([]*DimensionConfig, error)
LoadDimensionConfigs loads dimension configurations from the database
func (*DatabasePersistence) LoadDimensionConfigsByTenant ¶
func (dp *DatabasePersistence) LoadDimensionConfigsByTenant(ctx context.Context, tenantID, applicationID string) ([]*DimensionConfig, error)
LoadDimensionConfigsByTenant loads dimension configurations for a specific tenant and application from the database
func (*DatabasePersistence) LoadRules ¶
func (dp *DatabasePersistence) LoadRules(ctx context.Context) ([]*Rule, error)
LoadRules loads all rules from the database
func (*DatabasePersistence) LoadRulesByTenant ¶
func (dp *DatabasePersistence) LoadRulesByTenant(ctx context.Context, tenantID, applicationID string) ([]*Rule, error)
LoadRulesByTenant loads rules for a specific tenant and application from the database
func (*DatabasePersistence) SaveDimensionConfigs ¶
func (dp *DatabasePersistence) SaveDimensionConfigs(ctx context.Context, configs []*DimensionConfig) error
SaveDimensionConfigs saves dimension configurations to the database
type DimensionConfig ¶
type DimensionConfig struct {
Name string `json:"name"`
Index int `json:"index"` // Order of this dimension
Required bool `json:"required"` // Whether this dimension is required for matching
Weights map[MatchType]float64 `json:"weights"` // Weights for each match type
TenantID string `json:"tenant_id,omitempty"` // Tenant identifier for multi-tenancy
ApplicationID string `json:"application_id,omitempty"` // Application identifier for multi-application support
}
DimensionConfig defines the configuration for a dimension
func NewDimensionConfig ¶
func NewDimensionConfig(name string, index int, required bool) *DimensionConfig
NewDimensionConfig creates a DimensionConfig with empty weights map
func NewDimensionConfigWithWeights ¶
func NewDimensionConfigWithWeights(name string, index int, required bool, weights map[MatchType]float64) *DimensionConfig
NewDimensionConfigWithWeights creates a DimensionConfig with specific weights per match type
func (*DimensionConfig) Clone ¶
func (dc *DimensionConfig) Clone() *DimensionConfig
Clone clones current dimension config deeply
func (*DimensionConfig) GetWeight ¶
func (dc *DimensionConfig) GetWeight(matchType MatchType) (float64, bool)
GetWeight returns the weight for a specific match type, returning 0.0 if not configured
func (*DimensionConfig) SetWeight ¶
func (dc *DimensionConfig) SetWeight(matchType MatchType, weight float64) *DimensionConfig
SetWeight sets the weight for a specific match type
type DimensionConfigs ¶
type DimensionConfigs struct {
// contains filtered or unexported fields
}
DimensionConfigs manages dimension configurations with automatic sorting and provides read-only access to sorted dimension lists
func NewDimensionConfigs ¶
func NewDimensionConfigs() *DimensionConfigs
NewDimensionConfigs creates a new DimensionConfigs manager with default equal weight sorter
func NewDimensionConfigsWithDimensionsAndSorter ¶
func NewDimensionConfigsWithDimensionsAndSorter(dimensions []*DimensionConfig, sorter func([]*DimensionConfig)) *DimensionConfigs
NewDimensionConfigsWithSorter creates a new DimensionConfigs manager with custom sorter
func NewDimensionConfigsWithSorter ¶
func NewDimensionConfigsWithSorter(sorter func([]*DimensionConfig)) *DimensionConfigs
NewDimensionConfigsWithSorter creates a new DimensionConfigs manager with custom sorter
func (*DimensionConfigs) Add ¶
func (dc *DimensionConfigs) Add(config *DimensionConfig)
Add adds or updates a dimension config and automatically updates the sorted list
func (*DimensionConfigs) Clone ¶
func (dc *DimensionConfigs) Clone(dcs []*DimensionConfig) *DimensionConfigs
Clone returns a deep copied instance of current dimension configs with given configs merged
func (*DimensionConfigs) CloneDimension ¶
func (dc *DimensionConfigs) CloneDimension(name string) *DimensionConfig
CloneDimension returns a cloned dimension config if dimension exists
func (*DimensionConfigs) CloneSorted ¶
func (dc *DimensionConfigs) CloneSorted() []*DimensionConfig
Clone deep clone all dimension configs, a little heavy operator
func (*DimensionConfigs) Count ¶
func (dc *DimensionConfigs) Count() int
Count returns the number of dimension configs
func (*DimensionConfigs) Exist ¶
func (dc *DimensionConfigs) Exist(name string) bool
Exist checks the existence of given dimension name
func (*DimensionConfigs) Get ¶
func (dc *DimensionConfigs) Get(i int) (string, bool)
Get returns the dimension config at index i
func (*DimensionConfigs) GetSortedNames ¶
func (dc *DimensionConfigs) GetSortedNames() []string
GetSortedNames returns the sorted list of dimension names
func (*DimensionConfigs) GetWeight ¶
func (dc *DimensionConfigs) GetWeight(name string, mt MatchType) (float64, bool)
Get returns a dimension config by name (read-only)
func (*DimensionConfigs) IsRequired ¶
func (dc *DimensionConfigs) IsRequired(name string) bool
IsRequired returns whether the dimension is required or not
func (*DimensionConfigs) LoadBulk ¶
func (dc *DimensionConfigs) LoadBulk(configs []*DimensionConfig)
LoadBulk loads multiple dimension configs and sorts only once at the end This is more efficient than calling Add repeatedly during persistence loading
func (*DimensionConfigs) Remove ¶
func (dc *DimensionConfigs) Remove(dimensionName string) bool
Remove removes a dimension config and automatically updates the sorted list
func (*DimensionConfigs) SetSorter ¶
func (dc *DimensionConfigs) SetSorter(sorter func([]*DimensionConfig))
SetSorter sets a custom sorter function and re-sorts the configs
type DimensionEvent ¶
type DimensionEvent struct {
Dimension *DimensionConfig `json:"dimension"`
}
DimensionEvent represents dimension-related events
type DimensionValue ¶
type DimensionValue struct {
DimensionName string `json:"dimension_name"`
Value string `json:"value"`
MatchType MatchType `json:"match_type"`
}
DimensionValue represents a value for a specific dimension in a rule
type Event ¶
type Event struct {
Type EventType `json:"type"`
Timestamp time.Time `json:"timestamp"`
NodeID string `json:"node_id"` // ID of the node that published this event
Data interface{} `json:"data"`
}
Event represents an event from the message queue
type EventType ¶
type EventType string
EventType defines the type of events
const ( EventTypeRuleAdded EventType = "rule_added" EventTypeRuleUpdated EventType = "rule_updated" EventTypeRuleDeleted EventType = "rule_deleted" EventTypeDimensionAdded EventType = "dimension_added" EventTypeDimensionUpdated EventType = "dimension_updated" EventTypeDimensionDeleted EventType = "dimension_deleted" EventTypeRebuild EventType = "rebuild" // Indicates full state rebuild needed )
type ForestIndex ¶
type ForestIndex struct {
*RuleForest
}
ForestIndex provides backward compatibility by embedding RuleForest
type JSONPersistence ¶
type JSONPersistence struct {
// contains filtered or unexported fields
}
JSONPersistence implements PersistenceInterface using JSON files
func NewJSONPersistence ¶
func NewJSONPersistence(dataDir string) *JSONPersistence
NewJSONPersistence creates a new JSON persistence layer
func (*JSONPersistence) Health ¶
func (jp *JSONPersistence) Health(ctx context.Context) error
Health checks if the persistence layer is healthy
func (*JSONPersistence) LoadDimensionConfigs ¶
func (jp *JSONPersistence) LoadDimensionConfigs(ctx context.Context) ([]*DimensionConfig, error)
LoadDimensionConfigs loads dimension configurations from JSON file
func (*JSONPersistence) LoadDimensionConfigsByTenant ¶
func (jp *JSONPersistence) LoadDimensionConfigsByTenant(ctx context.Context, tenantID, applicationID string) ([]*DimensionConfig, error)
LoadDimensionConfigsByTenant loads dimension configurations for a specific tenant and application
func (*JSONPersistence) LoadRules ¶
func (jp *JSONPersistence) LoadRules(ctx context.Context) ([]*Rule, error)
LoadRules loads all rules from JSON file
func (*JSONPersistence) LoadRulesByTenant ¶
func (jp *JSONPersistence) LoadRulesByTenant(ctx context.Context, tenantID, applicationID string) ([]*Rule, error)
LoadRulesByTenant loads rules for a specific tenant and application
func (*JSONPersistence) SaveDimensionConfigs ¶
func (jp *JSONPersistence) SaveDimensionConfigs(ctx context.Context, configs []*DimensionConfig) error
SaveDimensionConfigs saves dimension configurations to JSON file
type KafkaEventSubscriber ¶
type KafkaEventSubscriber struct {
// contains filtered or unexported fields
}
KafkaEventSubscriber implements EventSubscriberInterface using Kafka Note: This is a basic example. In production, you'd use a proper Kafka client library
func NewKafkaEventSubscriber ¶
func NewKafkaEventSubscriber(brokers []string, topics []string, groupID string) *KafkaEventSubscriber
NewKafkaEventSubscriber creates a new Kafka event subscriber
func (*KafkaEventSubscriber) Close ¶
func (kes *KafkaEventSubscriber) Close() error
Close closes the Kafka subscriber
type LatestEvent ¶
type LatestEvent struct {
Timestamp int64 `json:"timestamp"` // Unix timestamp in nanoseconds for ordering
NodeID string `json:"node_id"` // Node that published this event
Event *Event `json:"event"` // The actual event
}
LatestEvent represents the latest event stored in Redis (single event only)
type MatchBranch ¶
type MatchBranch struct {
MatchType MatchType `json:"match_type"` // The match type for this branch
Rules []*Rule `json:"rules"` // Rules that use this match type at this level
Children map[string]*SharedNode `json:"children"` // Child nodes (key = dimension value)
}
MatchBranch represents a branch for a specific match type
type MatchResult ¶
type MatchResult struct {
Rule *Rule `json:"rule"`
TotalWeight float64 `json:"total_weight"`
MatchedDims int `json:"matched_dimensions"`
}
MatchResult represents the result of a rule matching operation
type MatcherEngine ¶
type MatcherEngine struct {
// contains filtered or unexported fields
}
MatcherEngine provides a simple, high-level API for the rule matching system
func NewMatcherEngine ¶
func NewMatcherEngine(ctx context.Context, persistence PersistenceInterface, broker Broker, nodeID string, dcs *DimensionConfigs, initialTimeout time.Duration) (*MatcherEngine, error)
NewMatcherEngine creates a new matcher engine with the specified persistence and event broker Note: ctx should not be cancelled in normal status
func NewMatcherEngineWithDefaults ¶
func NewMatcherEngineWithDefaults(dataDir string) (*MatcherEngine, error)
NewMatcherEngineWithDefaults creates a matcher engine with default JSON persistence
func (*MatcherEngine) AddAnyRule ¶
func (me *MatcherEngine) AddAnyRule(id string, dimensionNames []string, manualWeight float64) error
AddAnyRule creates a rule that matches any input with manual weight
func (*MatcherEngine) AddDimension ¶
func (me *MatcherEngine) AddDimension(config *DimensionConfig) error
AddDimension adds a new dimension configuration
func (*MatcherEngine) AddRule ¶
func (me *MatcherEngine) AddRule(rule *Rule) error
AddRule adds a rule to the engine
func (*MatcherEngine) AddSimpleRule ¶
func (me *MatcherEngine) AddSimpleRule(id string, dimensions map[string]string, manualWeight *float64) error
AddSimpleRule creates a rule with all exact matches
func (*MatcherEngine) AutoSave ¶
func (me *MatcherEngine) AutoSave(interval time.Duration) chan<- bool
AutoSave starts automatic saving at the specified interval
func (*MatcherEngine) BatchAddRules ¶
func (me *MatcherEngine) BatchAddRules(rules []*Rule) error
BatchAddRules adds multiple rules in a single operation
func (*MatcherEngine) ClearCache ¶
func (me *MatcherEngine) ClearCache()
ClearCache clears the query cache
func (*MatcherEngine) Close ¶
func (me *MatcherEngine) Close() error
Close closes the engine and cleans up resources
func (*MatcherEngine) DeleteRule ¶
func (me *MatcherEngine) DeleteRule(ruleID string) error
DeleteRule removes a rule by ID
func (*MatcherEngine) FindAllMatches ¶
func (me *MatcherEngine) FindAllMatches(query *QueryRule) ([]*MatchResult, error)
FindAllMatches finds all matching rules for a query
func (*MatcherEngine) FindAllMatchesInBatch ¶
func (me *MatcherEngine) FindAllMatchesInBatch(query ...*QueryRule) ([][]*MatchResult, error)
FindAllMatches finds all matching rules for a query
func (*MatcherEngine) FindBestMatch ¶
func (me *MatcherEngine) FindBestMatch(query *QueryRule) (*MatchResult, error)
FindBestMatch finds the best matching rule for a query
func (*MatcherEngine) FindBestMatchInBatch ¶
func (me *MatcherEngine) FindBestMatchInBatch(queries ...*QueryRule) ([]*MatchResult, error)
FindBestMatchInBatch runs multiple queries under a single matcher read-lock and returns the best match for each query in the same order. This provides an atomic snapshot view for a group of queries with respect to concurrent updates.
func (*MatcherEngine) GetCacheStats ¶
func (me *MatcherEngine) GetCacheStats() map[string]interface{}
GetCacheStats returns cache statistics
func (*MatcherEngine) GetDimensionConfigs ¶
func (me *MatcherEngine) GetDimensionConfigs() *DimensionConfigs
GetDimensionConfigs returns deep cloned DimensionConfigs instance
func (*MatcherEngine) GetForestStats ¶
func (me *MatcherEngine) GetForestStats() map[string]interface{}
GetForestStats returns detailed forest index statistics
func (*MatcherEngine) GetRule ¶
func (me *MatcherEngine) GetRule(ruleID string) (*Rule, error)
GetRule retrieves a rule by ID
func (*MatcherEngine) GetStats ¶
func (me *MatcherEngine) GetStats() *MatcherStats
GetStats returns current engine statistics
func (*MatcherEngine) Health ¶
func (me *MatcherEngine) Health() error
Health checks if the engine is healthy
func (*MatcherEngine) ListDimensions ¶
func (me *MatcherEngine) ListDimensions() ([]*DimensionConfig, error)
ListDimensions returns all dimension configurations
func (*MatcherEngine) ListRules ¶
func (me *MatcherEngine) ListRules(offset, limit int) ([]*Rule, error)
ListRules returns all rules with pagination
func (*MatcherEngine) LoadDimensions ¶
func (me *MatcherEngine) LoadDimensions(configs []*DimensionConfig)
LoadDimensions loads all dimensions in bulk
func (*MatcherEngine) Rebuild ¶
func (me *MatcherEngine) Rebuild() error
Rebuild rebuilds the forest index (useful after bulk operations)
func (*MatcherEngine) Save ¶
func (me *MatcherEngine) Save() error
Save saves the current state to persistence
func (*MatcherEngine) SaveToPersistence ¶
func (me *MatcherEngine) SaveToPersistence() error
func (*MatcherEngine) SetAllowDuplicateWeights ¶
func (me *MatcherEngine) SetAllowDuplicateWeights(allow bool)
SetAllowDuplicateWeights configures whether rules with duplicate weights are allowed By default, duplicate weights are not allowed to ensure deterministic matching
func (*MatcherEngine) UpdateRule ¶
func (me *MatcherEngine) UpdateRule(rule *Rule) error
UpdateRule updates an existing rule
func (*MatcherEngine) UpdateRuleMetadata ¶
func (me *MatcherEngine) UpdateRuleMetadata(ruleID string, metadata map[string]string) error
UpdateRuleMetadata updates only the metadata of an existing rule
func (*MatcherEngine) UpdateRuleStatus ¶
func (me *MatcherEngine) UpdateRuleStatus(ruleID string, status RuleStatus) error
UpdateRuleStatus updates only the status of an existing rule
func (*MatcherEngine) ValidateRule ¶
func (me *MatcherEngine) ValidateRule(rule *Rule) error
ValidateRule validates a rule before adding it
type MatcherStats ¶
type MatcherStats struct {
AverageQueryTime int64 `json:"average_query_time"`
TotalRules int `json:"total_rules"`
TotalDimensions int `json:"total_dimensions"`
TotalQueries int64 `json:"total_queries"`
TotalQueryTime int64 `json:"total_query_time"`
CacheHitRate float64 `json:"cache_hit_rate"`
LastUpdated time.Time `json:"last_updated"`
}
MatcherStats provides statistics about the matcher
type MemoryMatcherEngine ¶
type MemoryMatcherEngine struct {
// contains filtered or unexported fields
}
MemoryMatcherEngine implements the core matching logic using forest indexes
func (*MemoryMatcherEngine) AddDimension ¶
func (m *MemoryMatcherEngine) AddDimension(config *DimensionConfig) error
AddDimension adds a new dimension configuration
func (*MemoryMatcherEngine) AddRule ¶
func (m *MemoryMatcherEngine) AddRule(rule *Rule) error
AddRule adds a new rule to the matcher
func (*MemoryMatcherEngine) Close ¶
func (m *MemoryMatcherEngine) Close() error
Close closes the matcher and cleans up resources
func (*MemoryMatcherEngine) DeleteRule ¶
func (m *MemoryMatcherEngine) DeleteRule(ruleID string) error
DeleteRule removes a rule from the matcher
func (*MemoryMatcherEngine) FindAllMatches ¶
func (m *MemoryMatcherEngine) FindAllMatches(query *QueryRule) ([]*MatchResult, error)
FindAllMatches finds all matching rules for a query
func (*MemoryMatcherEngine) FindAllMatchesInBatch ¶
func (m *MemoryMatcherEngine) FindAllMatchesInBatch(queries []*QueryRule) ([][]*MatchResult, error)
FindAllMatchesInBatch finds the best matching rule for each query in the provided slice and returns results in the same order. The entire operation is performed while holding the matcher's read lock so the caller sees a consistent snapshot with respect to concurrent updates.
func (*MemoryMatcherEngine) FindBestMatch ¶
func (m *MemoryMatcherEngine) FindBestMatch(query *QueryRule) (*MatchResult, error)
FindBestMatch finds the best matching rule for a query
func (*MemoryMatcherEngine) FindBestMatchInBatch ¶
func (m *MemoryMatcherEngine) FindBestMatchInBatch(queries []*QueryRule) ([]*MatchResult, error)
FindBestMatchInBatch finds the best matching rule for each query in the provided slice and returns results in the same order. The entire operation is performed while holding the matcher's read lock so the caller sees a consistent snapshot with respect to concurrent updates.
func (*MemoryMatcherEngine) GetDimensionConfigs ¶
func (m *MemoryMatcherEngine) GetDimensionConfigs() *DimensionConfigs
GetDimensionConfigs returns a deep copy of DimensionConfigs
func (*MemoryMatcherEngine) GetRule ¶
func (m *MemoryMatcherEngine) GetRule(ruleID string) (*Rule, error)
GetRule retrieves a rule by ID (public method)
func (*MemoryMatcherEngine) GetStats ¶
func (m *MemoryMatcherEngine) GetStats() *MatcherStats
GetStats returns current statistics
func (*MemoryMatcherEngine) Health ¶
func (m *MemoryMatcherEngine) Health() error
Health checks if the matcher is healthy
func (*MemoryMatcherEngine) ListDimensions ¶
func (m *MemoryMatcherEngine) ListDimensions() ([]*DimensionConfig, error)
ListDimensions returns all dimension configurations
func (*MemoryMatcherEngine) ListRules ¶
func (m *MemoryMatcherEngine) ListRules(offset, limit int) ([]*Rule, error)
ListRules returns all rules with pagination
func (*MemoryMatcherEngine) LoadDimensions ¶
func (m *MemoryMatcherEngine) LoadDimensions(configs []*DimensionConfig)
LoadDimensions loads dimensions in bulk
func (*MemoryMatcherEngine) Rebuild ¶
func (m *MemoryMatcherEngine) Rebuild() error
Rebuild clears all data and rebuilds the forest from the persistence interface
func (*MemoryMatcherEngine) SaveToPersistence ¶
func (m *MemoryMatcherEngine) SaveToPersistence() error
SaveToPersistence saves current state to persistence layer
func (*MemoryMatcherEngine) SetAllowDuplicateWeights ¶
func (m *MemoryMatcherEngine) SetAllowDuplicateWeights(allow bool)
SetAllowDuplicateWeights configures whether rules with duplicate weights are allowed By default, duplicate weights are not allowed to ensure deterministic matching
func (*MemoryMatcherEngine) UpdateRule ¶
func (m *MemoryMatcherEngine) UpdateRule(rule *Rule) error
UpdateRule updates an existing rule (public method)
type MockEventSubscriber ¶
type MockEventSubscriber struct {
// contains filtered or unexported fields
}
MockEventSubscriber is a mock implementation for testing
func NewMockEventSubscriber ¶
func NewMockEventSubscriber() *MockEventSubscriber
NewMockEventSubscriber creates a new mock event subscriber
func (*MockEventSubscriber) Close ¶
func (mes *MockEventSubscriber) Close() error
Close closes the subscriber
func (*MockEventSubscriber) Health ¶
func (mes *MockEventSubscriber) Health(ctx context.Context) error
Health checks if the subscriber is healthy
func (*MockEventSubscriber) Publish ¶
func (mes *MockEventSubscriber) Publish(ctx context.Context, event *Event) error
Publish publishes an event to the mock broker
func (*MockEventSubscriber) PublishEvent ¶
func (mes *MockEventSubscriber) PublishEvent(event *Event)
PublishEvent publishes an event (for testing) - deprecated, use Publish instead
type MultiLevelCache ¶
type MultiLevelCache struct {
// contains filtered or unexported fields
}
MultiLevelCache implements a multi-level cache system
func NewMultiLevelCache ¶
func NewMultiLevelCache(l1Size int, l1TTL time.Duration, l2Size int, l2TTL time.Duration) *MultiLevelCache
NewMultiLevelCache creates a new multi-level cache
func (*MultiLevelCache) Get ¶
func (mlc *MultiLevelCache) Get(query *QueryRule) *MatchResult
Get retrieves a result from the multi-level cache
func (*MultiLevelCache) Set ¶
func (mlc *MultiLevelCache) Set(query *QueryRule, result *MatchResult)
Set stores a result in both cache levels
func (*MultiLevelCache) Stats ¶
func (mlc *MultiLevelCache) Stats() map[string]interface{}
Stats returns comprehensive cache statistics
type PersistenceInterface ¶
type PersistenceInterface interface {
// Rules operations
LoadRules(ctx context.Context) ([]*Rule, error)
LoadRulesByTenant(ctx context.Context, tenantID, applicationID string) ([]*Rule, error)
SaveRules(ctx context.Context, rules []*Rule) error
// Dimensions operations
LoadDimensionConfigs(ctx context.Context) ([]*DimensionConfig, error)
LoadDimensionConfigsByTenant(ctx context.Context, tenantID, applicationID string) ([]*DimensionConfig, error)
SaveDimensionConfigs(ctx context.Context, configs []*DimensionConfig) error
// Health check
Health(ctx context.Context) error
}
PersistenceInterface defines the interface for data persistence
type QueryCache ¶
type QueryCache struct {
// contains filtered or unexported fields
}
QueryCache implements a thread-safe LRU cache for query results
func NewQueryCache ¶
func NewQueryCache(maxSize int, defaultTTL time.Duration) *QueryCache
NewQueryCache creates a new query cache
func (*QueryCache) CleanupExpired ¶
func (qc *QueryCache) CleanupExpired() int
CleanupExpired removes all expired entries from the cache
func (*QueryCache) Get ¶
func (qc *QueryCache) Get(query *QueryRule) *MatchResult
Get retrieves a cached result for a query
func (*QueryCache) Set ¶
func (qc *QueryCache) Set(query *QueryRule, result *MatchResult)
Set stores a result in the cache
func (*QueryCache) SetWithTTL ¶
func (qc *QueryCache) SetWithTTL(query *QueryRule, result *MatchResult, ttl time.Duration)
SetWithTTL stores a result in the cache with custom TTL
func (*QueryCache) Size ¶
func (qc *QueryCache) Size() int
Size returns the current number of entries in the cache
func (*QueryCache) StartCleanupWorker ¶
func (qc *QueryCache) StartCleanupWorker(interval time.Duration) chan<- bool
StartCleanupWorker starts a background worker to clean up expired entries
func (*QueryCache) Stats ¶
func (qc *QueryCache) Stats() map[string]interface{}
Stats returns cache statistics
type QueryRule ¶
type QueryRule struct {
TenantID string `json:"tenant_id,omitempty"`
ApplicationID string `json:"application_id,omitempty"`
Values map[string]string `json:"values"`
IncludeAllRules bool `json:"include_all_rules,omitempty"`
DynamicDimensionConfigs *DimensionConfigs `json:"dynamic_dimension_configs,omitempty"`
ExcludeRules map[string]bool `json:"exclude_rules,omitempty"`
}
QueryRule represents a query with values for each dimension
func CreateQuery ¶
CreateQuery creates a query from a map of dimension values
func CreateQueryWithAllRules ¶
CreateQueryWithAllRules creates a query that includes all rules (working and draft)
func CreateQueryWithAllRulesAndDynamicConfigs ¶
func CreateQueryWithAllRulesAndDynamicConfigs(values map[string]string, dynamicConfigs *DimensionConfigs) *QueryRule
CreateQueryWithAllRulesAndDynamicConfigs creates a query that includes all rules and uses custom dimension configurations
func CreateQueryWithAllRulesAndExcluded ¶
func CreateQueryWithAllRulesAndExcluded(values map[string]string, excludeRuleIDs []string) *QueryRule
CreateQueryWithAllRulesAndExcluded creates a query that includes all rules but excludes specific ones
func CreateQueryWithAllRulesAndTenant ¶
func CreateQueryWithAllRulesAndTenant(tenantID, applicationID string, values map[string]string) *QueryRule
CreateQueryWithAllRulesAndTenant creates a tenant-scoped query that includes all rules
func CreateQueryWithAllRulesTenantAndDynamicConfigs ¶
func CreateQueryWithAllRulesTenantAndDynamicConfigs(tenantID, applicationID string, values map[string]string, dynamicConfigs *DimensionConfigs) *QueryRule
CreateQueryWithAllRulesTenantAndDynamicConfigs creates a comprehensive query with all options
func CreateQueryWithAllRulesTenantAndExcluded ¶
func CreateQueryWithAllRulesTenantAndExcluded(tenantID, applicationID string, values map[string]string, excludeRuleIDs []string) *QueryRule
CreateQueryWithAllRulesTenantAndExcluded creates a comprehensive query with tenant scope, all rules, and exclusions
func CreateQueryWithDynamicConfigs ¶
func CreateQueryWithDynamicConfigs(values map[string]string, dynamicConfigs *DimensionConfigs) *QueryRule
CreateQueryWithDynamicConfigs creates a query with custom dimension configurations This allows for dynamic weight adjustment per query without modifying the global configs
func CreateQueryWithExcludedRules ¶
CreateQueryWithExcludedRules creates a query that excludes specific rules by ID
func CreateQueryWithTenant ¶
CreateQueryWithTenant creates a query for a specific tenant and application
func CreateQueryWithTenantAndDynamicConfigs ¶
func CreateQueryWithTenantAndDynamicConfigs(tenantID, applicationID string, values map[string]string, dynamicConfigs *DimensionConfigs) *QueryRule
CreateQueryWithTenantAndDynamicConfigs creates a tenant-scoped query with custom dimension configurations
func CreateQueryWithTenantAndExcluded ¶
func CreateQueryWithTenantAndExcluded(tenantID, applicationID string, values map[string]string, excludeRuleIDs []string) *QueryRule
CreateQueryWithTenantAndExcluded creates a tenant-scoped query with excluded rules
func (*QueryRule) GetTenantContext ¶
GetTenantContext returns the tenant and application context for the query
type RedisBroker ¶
type RedisBroker struct {
// contains filtered or unexported fields
}
RedisBroker implements Broker using Redis Streams
func NewRedisEventBroker ¶
func NewRedisEventBroker(config RedisEventBrokerConfig) (*RedisBroker, error)
NewRedisEventBroker creates a new Redis-based event broker
func (*RedisBroker) Health ¶
func (r *RedisBroker) Health(ctx context.Context) error
Health checks the health of the Redis connection
type RedisCASBroker ¶
type RedisCASBroker struct {
// contains filtered or unexported fields
}
RedisCASBroker implements Broker using Redis with Compare-And-Swap operations It uses a fixed event key for CAS operations - no initialization, only latest event
func NewClusterRedisCASBroker ¶
func NewClusterRedisCASBroker(addrs []string, password, nodeID string) (*RedisCASBroker, error)
NewClusterRedisCASBroker creates a Redis CAS broker for cluster deployment
func NewRedisCASBroker ¶
func NewRedisCASBroker(config RedisCASConfig) (*RedisCASBroker, error)
NewRedisCASBroker creates a new Redis CAS-based broker Auto-detects deployment type based on configuration: - Single address without MasterName = Single node - Multiple addresses without MasterName = Cluster - MasterName provided = Sentinel (addresses are sentinel servers) Does NOT initialize any default values in Redis
func NewSentinelRedisCASBroker ¶
func NewSentinelRedisCASBroker(sentinelAddrs []string, masterName, password, nodeID string) (*RedisCASBroker, error)
NewSentinelRedisCASBroker creates a Redis CAS broker for sentinel deployment
func NewSingleNodeRedisCASBroker ¶
func NewSingleNodeRedisCASBroker(addr, password, nodeID string) (*RedisCASBroker, error)
NewSingleNodeRedisCASBroker creates a Redis CAS broker for single node deployment
func (*RedisCASBroker) Close ¶
func (r *RedisCASBroker) Close() error
Close closes the Redis CAS broker
func (*RedisCASBroker) GetLastTimestamp ¶
func (r *RedisCASBroker) GetLastTimestamp() int64
GetLastTimestamp returns the last known event timestamp
func (*RedisCASBroker) GetLatestEvent ¶
func (r *RedisCASBroker) GetLatestEvent(ctx context.Context) (*LatestEvent, error)
GetLatestEvent returns the current latest event from Redis (for debugging/testing)
func (*RedisCASBroker) Health ¶
func (r *RedisCASBroker) Health(ctx context.Context) error
Health checks the health of the Redis connection
func (*RedisCASBroker) Publish ¶
func (r *RedisCASBroker) Publish(ctx context.Context, event *Event) error
Publish publishes an event using CAS operation
func (*RedisCASBroker) Subscribe ¶
func (r *RedisCASBroker) Subscribe(ctx context.Context, events chan<- *Event) error
Subscribe starts listening for events by polling the Redis key
func (*RedisCASBroker) WaitForTimestamp ¶
func (r *RedisCASBroker) WaitForTimestamp(ctx context.Context, targetTimestamp int64, timeout time.Duration) error
WaitForTimestamp waits for events to reach at least the specified timestamp
type RedisCASConfig ¶
type RedisCASConfig struct {
// Redis server configuration (auto-detects deployment type)
Addrs []string // Redis server addresses - single for standalone, multiple for cluster/sentinel
MasterName string // Master name for sentinel deployment (if provided, Addrs are sentinel servers)
// Authentication
Username string // Redis username (for Redis 6.0+ ACL)
Password string // Redis password
SentinelUser string // Sentinel username (for sentinel deployment)
SentinelPasswd string // Sentinel password (for sentinel deployment)
DB int // Redis database number (ignored for cluster)
// Connection settings
MaxRetries int // Maximum number of retries (default: 3)
MinRetryBackoff time.Duration // Minimum backoff between retries (default: 8ms)
MaxRetryBackoff time.Duration // Maximum backoff between retries (default: 512ms)
DialTimeout time.Duration // Dial timeout (default: 5s)
ReadTimeout time.Duration // Read timeout (default: 3s)
WriteTimeout time.Duration // Write timeout (default: 3s)
PoolSize int // Connection pool size (default: 10 per CPU)
MinIdleConns int // Minimum idle connections (default: 0)
// TLS configuration
TLSEnabled bool // Enable TLS
TLSInsecureSkip bool // Skip certificate verification
TLSServerName string // Server name for certificate verification
TLSCertFile string // Client certificate file path
TLSKeyFile string // Client private key file path
TLSCAFile string // CA certificate file path
// Broker-specific configuration
NodeID string // Node identifier (required)
Namespace string // Namespace for keys (optional, defaults to "matcher")
PollInterval time.Duration // How often to poll for changes (defaults to 2s, should be 1-5s)
}
RedisCASConfig holds configuration for Redis CAS broker Auto-detects deployment type based on provided parameters: - Single address without MasterName = Single node - Multiple addresses without MasterName = Cluster - MasterName provided = Sentinel (addresses are sentinel servers)
type RedisClientInterface ¶
type RedisClientInterface interface {
Get(ctx context.Context, key string) *redis.StringCmd
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.StatusCmd
Watch(ctx context.Context, fn func(*redis.Tx) error, keys ...string) error
TxPipelined(ctx context.Context, fn func(redis.Pipeliner) error) ([]redis.Cmder, error)
Ping(ctx context.Context) *redis.StatusCmd
Close() error
}
RedisClientInterface defines the common interface for all Redis client types
type RedisEventBrokerConfig ¶
type RedisEventBrokerConfig struct {
RedisAddr string // Redis server address (e.g., "localhost:6379")
Password string // Redis password (empty if no password)
DB int // Redis database number
StreamName string // Redis stream name for events
ConsumerGroup string // Consumer group name
ConsumerName string // Consumer name within the group
NodeID string // Node identifier
}
RedisEventBrokerConfig holds configuration for Redis event broker
type Rule ¶
type Rule struct {
ID string `json:"id"`
TenantID string `json:"tenant_id,omitempty"` // Tenant identifier for multi-tenancy
ApplicationID string `json:"application_id,omitempty"` // Application identifier for multi-application support
Dimensions map[string]*DimensionValue `json:"dimensions"`
ManualWeight *float64 `json:"manual_weight,omitempty"` // Optional manual weight override
Status RuleStatus `json:"status"` // Status of the rule (working, draft, etc.)
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Metadata map[string]string `json:"metadata,omitempty"` // Additional metadata
}
Rule represents a matching rule with dynamic dimensions
func (*Rule) CalculateTotalWeight ¶
func (r *Rule) CalculateTotalWeight(dimensionConfigs *DimensionConfigs) float64
CalculateTotalWeight calculates the total weight of the rule using dimension configurations
func (*Rule) CloneAndComplete ¶
CloneAndComplete creates a deep copy of the Rule and fill in dimensions
func (*Rule) GetDimensionMatchType ¶
GetDimensionMatchType returns the match type for a specific dimension in the rule
func (*Rule) GetDimensionValue ¶
func (r *Rule) GetDimensionValue(dimensionName string) *DimensionValue
GetDimensionValue returns the value for a specific dimension in the rule
func (*Rule) GetTenantContext ¶
GetTenantContext returns the tenant and application context for the rule
func (*Rule) HasDimension ¶
HasDimension checks if the rule has a specific dimension
func (*Rule) MatchesTenantContext ¶
MatchesTenantContext checks if the rule matches the given tenant and application context
type RuleBuilder ¶
type RuleBuilder struct {
// contains filtered or unexported fields
}
RuleBuilder provides a fluent API for building rules
func NewRuleWithTenant ¶
func NewRuleWithTenant(id, tenantID, applicationID string) *RuleBuilder
NewRuleWithTenant creates a new rule builder for a specific tenant and application
func (*RuleBuilder) Application ¶
func (rb *RuleBuilder) Application(applicationID string) *RuleBuilder
Application sets the application ID for the rule
func (*RuleBuilder) Dimension ¶
func (rb *RuleBuilder) Dimension(name, value string, matchType MatchType) *RuleBuilder
Dimension adds a dimension to the rule being built The weight will be automatically populated from dimension configuration when the rule is added to the engine
func (*RuleBuilder) ManualWeight ¶
func (rb *RuleBuilder) ManualWeight(weight float64) *RuleBuilder
ManualWeight sets a manual weight override for the rule
func (*RuleBuilder) Metadata ¶
func (rb *RuleBuilder) Metadata(key, value string) *RuleBuilder
Metadata adds metadata to the rule
func (*RuleBuilder) Status ¶
func (rb *RuleBuilder) Status(status RuleStatus) *RuleBuilder
Status sets the status of the rule
func (*RuleBuilder) Tenant ¶
func (rb *RuleBuilder) Tenant(tenantID string) *RuleBuilder
Tenant sets the tenant ID for the rule
type RuleEvent ¶
type RuleEvent struct {
Rule *Rule `json:"rule"`
}
RuleEvent represents rule-related events
type RuleForest ¶
type RuleForest struct {
TenantID string `json:"tenant_id,omitempty"` // Tenant identifier for this forest
ApplicationID string `json:"application_id,omitempty"` // Application identifier for this forest
Trees map[MatchType][]*SharedNode `json:"trees"` // Trees organized by first dimension match type
EqualTreesIndex map[string]*SharedNode `json:"-"` // Hash map index for O(1) lookup of equal match trees by first dimension value
Dimensions *DimensionConfigs `json:"dimension_order"` // Order of dimensions for tree traversal
RuleIndex map[string][]*SharedNode `json:"rule_index"` // Index of rules to their nodes for quick removal
NodeRelationships map[string]map[string]string `json:"-"` // Efficient relationship map for fast dumping: current_node -> rule_id -> next_node
// contains filtered or unexported fields
}
RuleForest represents the forest structure with shared nodes
func CreateForestIndexCompat ¶
func CreateForestIndexCompat() *RuleForest
CreateForestIndexCompat creates a forest index compatible with the old interface
func CreateRuleForest ¶
func CreateRuleForest(dimensionConfigs *DimensionConfigs) *RuleForest
CreateRuleForest creates a rule forest with the structure
func CreateRuleForestWithTenant ¶
func CreateRuleForestWithTenant(tenantID, applicationID string, dimensionConfigs *DimensionConfigs) *RuleForest
CreateRuleForestWithTenant creates a rule forest for a specific tenant and application
func (*RuleForest) AddRule ¶
func (rf *RuleForest) AddRule(rule *Rule) (*Rule, error)
AddRule adds a rule to the forest following the dimension order
func (*RuleForest) FindCandidateRules ¶
func (rf *RuleForest) FindCandidateRules(queryValues interface{}) []RuleWithWeight
FindCandidateRules finds rules that could match the query (map interface for compatibility)
func (*RuleForest) GetStats ¶
func (rf *RuleForest) GetStats() map[string]interface{}
GetStats returns statistics about the forest
func (*RuleForest) InitializeDimension ¶
func (rf *RuleForest) InitializeDimension(dimensionName string)
InitializeDimension is a compatibility method (no-op in the implementation)
func (*RuleForest) RemoveRule ¶
func (rf *RuleForest) RemoveRule(rule *Rule)
RemoveRule removes a rule from the forest
func (*RuleForest) ReplaceRule ¶
func (rf *RuleForest) ReplaceRule(oldRule, newRule *Rule) error
ReplaceRule atomically replaces one rule with another to prevent partial state visibility This method ensures no intermediate state where both rules coexist in the forest
type RuleStatus ¶
type RuleStatus string
RuleStatus defines the status of a rule
const ( RuleStatusWorking RuleStatus = "working" RuleStatusDraft RuleStatus = "draft" )
type RuleWithWeight ¶
RuleWithWeight can be used as search candidates
type SharedNode ¶
type SharedNode struct {
// contains filtered or unexported fields
}
SharedNode represents a node in the forest where rules share paths Each node can have multiple branches based on different match types
func CreateSharedNode ¶
func CreateSharedNode(level int, dimensionName, value string) *SharedNode
CreateSharedNode creates a shared node
func (*SharedNode) AddRule ¶
func (sn *SharedNode) AddRule(rule *Rule, matchType MatchType)
AddRule adds a rule to this node for a specific match type (only for leaf nodes)
func (*SharedNode) RemoveRule ¶
func (sn *SharedNode) RemoveRule(ruleID string) bool
RemoveRule removes a rule from this node
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
debug_matching
command
|
|
|
performance_benchmark
command
|
|
|
smatcher
command
|
|
|
target_performance
command
|
|
|
dimension_consistency
command
|
|
|
forest_demo
command
|
|
|
multitenant_demo
command
|
|
|
weight_removal_demo
command
|