Documentation
¶
Overview ¶
Package ruleix implements a strongly typed in-memory rule index.
Example (MultiColumnRules) ¶
package main
import (
"cmp"
"fmt"
"github.com/typomaker/ruleix"
)
func main() {
type targetingConstraint struct {
country *string
tier *string
minimumTotal *int
excludedChannel *string
}
schema := ruleix.All(
ruleix.Include(ruleix.GetterFromPointer(func(c targetingConstraint) *string { return c.country })),
ruleix.Include(ruleix.GetterFromPointer(func(c targetingConstraint) *string { return c.tier })),
ruleix.GreaterOrEqual(ruleix.GetterFromPointer(func(c targetingConstraint) *int { return c.minimumTotal }), cmp.Compare[int]),
ruleix.Exclude(ruleix.GetterFromPointer(func(c targetingConstraint) *string { return c.excludedChannel })),
)
countryDE := "DE"
tierGold := "gold"
minimum100 := 100
marketplace := "marketplace"
constraints := []targetingConstraint{
{
country: &countryDE,
tier: &tierGold,
minimumTotal: &minimum100,
excludedChannel: &marketplace,
},
{country: &countryDE},
{},
}
ids := []string{"gold-de", "all-de", "global"}
entries := ruleix.Zip(constraints, ids)
index, err := ruleix.New[targetingConstraint, string](schema).Build(entries)
if err != nil {
panic(err)
}
minimum150 := 150
web := "web"
query := targetingConstraint{
country: &countryDE,
tier: &tierGold,
minimumTotal: &minimum150,
excludedChannel: &web,
}
found := make([][]string, 1)
index.Search([]targetingConstraint{query}, found)
matches := found[0]
fmt.Println(matches)
}
Output: [gold-de all-de global]
Index ¶
- func Zip[C any, ID any](constraints []C, ids []ID) iter.Seq2[C, ID]
- type Builder
- type Compare
- type Getter
- type Histogram
- type Index
- type Inspector
- type InspectorSnapshot
- func (s InspectorSnapshot) Bound() bool
- func (s InspectorSnapshot) CacheAdmission() uint64
- func (s InspectorSnapshot) CacheEviction() uint64
- func (s InspectorSnapshot) CacheExpansion() uint64
- func (s InspectorSnapshot) CacheHit() uint64
- func (s InspectorSnapshot) CacheMiss() uint64
- func (s InspectorSnapshot) CandidateCheck() uint64
- func (s InspectorSnapshot) DistinctValueCount() (uint64, bool)
- func (s InspectorSnapshot) EmptyResult() uint64
- func (s InspectorSnapshot) EntryCount() uint64
- func (s InspectorSnapshot) FalsePositiveRate() (float64, bool)
- func (s InspectorSnapshot) Granularity() (uint64, bool)
- func (s InspectorSnapshot) ItemCount() (uint64, bool)
- func (s InspectorSnapshot) MemoryLimit() (uint64, bool)
- func (s InspectorSnapshot) MemoryUsage() (uint64, bool)
- func (s InspectorSnapshot) Mode() RuleMode
- func (s InspectorSnapshot) RangePruning() uint64
- func (s InspectorSnapshot) ResultCardinality() Histogram
- func (s InspectorSnapshot) RuleCount() uint64
- func (s InspectorSnapshot) Strategy() string
- type LossyOption
- type Operator
- type Rule
- func All[T any](rules ...Rule[T]) Rule[T]
- func Between[T any, V any](from, until Getter[T, V], compare Compare[V]) Rule[T]
- func CompareBy[T any, V any](value Getter[T, V], operator Getter[T, Operator], compare Compare[V]) Rule[T]
- func Exclude[T any, V comparable](get Getter[T, V]) Rule[T]
- func Greater[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]
- func GreaterOrEqual[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]
- func Include[T any, V comparable](get Getter[T, V]) Rule[T]
- func Inspect[T any](dst *Inspector, rule Rule[T]) Rule[T]
- func Less[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]
- func LessOrEqual[T any, V any](get Getter[T, V], compare Compare[V]) Rule[T]
- func Lossy[T any](rule Rule[T], options ...LossyOption) Rule[T]
- type RuleMode
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Builder ¶
type Builder[C any, ID comparable] struct { // contains filtered or unexported fields }
Builder constructs immutable indexes from the same Rule schema. A Builder is not safe for concurrent calls to Build; callers that need them must provide their own synchronization. Indexes returned by completed builds are independent and safe for concurrent use.
func New ¶
func New[C any, ID comparable](schema Rule[C]) *Builder[C, ID]
New constructs a Builder from a strongly typed rule schema. New panics when schema is nil.
func (*Builder[C, ID]) Build ¶
Build consumes entries and returns an immutable, concurrently searchable Index. Constraints that share an external ID are combined under that ID, which is returned at most once by a search. Build must not be called concurrently on the same Builder; the library deliberately leaves synchronization of builds to the caller. A failed build does not prevent later calls.
type Compare ¶
Compare defines an ordering for values used by ordered filters. It returns a negative number when a < b, zero when a == b, and a positive number when a > b. Compare must define a stable, transitive total order for every value supplied during Build and Search. The standard library's cmp.Compare is suitable for ordered types.
type Getter ¶
Getter returns a value and reports whether it is present. A missing value is interpreted as a wildcard by filters. The boolean keeps zero values distinct from missing values without requiring pointers or heap allocations.
func GetterFromPointer ¶
GetterFromPointer adapts an old pointer getter during migration. New schemas should return (value, ok) directly to avoid pointers to temporary values.
type Histogram ¶
type Histogram struct {
Zero, One, TwoToFour, FiveToSixteen, SeventeenTo256, Above256 uint64
}
Histogram groups observed values into stable, allocation-free bins. Each bin includes its lower bound and excludes the next bin's lower bound.
type Index ¶
type Index[C any, ID comparable] struct { // contains filtered or unexported fields }
Index maps query values to the unique IDs of all matching stored constraints. It is immutable after Build and safe for concurrent calls to Search.
func (*Index[C, ID]) Search ¶
func (ix *Index[C, ID]) Search(conditions []C, found [][]ID)
Search appends the matches for conditions[i] to found[i], preserving first-insertion ID order and existing destination elements. The outer slices must have equal lengths; a mismatch panics before any result is changed. Empty batches do no work. Each call owns and releases its internal context. Callers must not concurrently mutate inputs or destinations, and destination backing arrays must not overlap.
Example ¶
package main
import (
"fmt"
"github.com/typomaker/ruleix"
)
func main() {
type constraint struct {
store *int
region *int
}
pointer := func(value int) *int { return &value }
entries := ruleix.Zip(
[]constraint{
{},
{store: pointer(10)},
{store: pointer(10), region: pointer(20)},
{store: pointer(10), region: pointer(30)},
},
[]string{"global", "store", "region-20", "region-30"},
)
index, err := ruleix.New[constraint, string](ruleix.All(
ruleix.Include(ruleix.GetterFromPointer(func(c constraint) *int { return c.store })),
ruleix.Include(ruleix.GetterFromPointer(func(c constraint) *int { return c.region })),
)).Build(entries)
if err != nil {
panic(err)
}
conditions := []constraint{
{store: pointer(10), region: pointer(20)},
{store: pointer(10), region: pointer(30)},
}
found := make([][]string, len(conditions))
index.Search(conditions, found)
for _, matches := range found {
fmt.Println(matches)
}
}
Output: [global store region-20] [global store region-30]
type Inspector ¶
type Inspector interface {
Snapshot() InspectorSnapshot
// contains filtered or unexported methods
}
Inspector captures immutable views of one rule's compiled representation and accumulated runtime metrics. Inspect selects and assigns the implementation when it decorates a rule.
type InspectorSnapshot ¶
type InspectorSnapshot struct {
// contains filtered or unexported fields
}
InspectorSnapshot is a coherent view of the build generation selected by one Snapshot call and the runtime counters observed during that call.
func (InspectorSnapshot) Bound ¶
func (s InspectorSnapshot) Bound() bool
Bound reports whether the snapshot belongs to a successful build.
func (InspectorSnapshot) CacheAdmission ¶
func (s InspectorSnapshot) CacheAdmission() uint64
CacheAdmission reports observed cache admissions.
func (InspectorSnapshot) CacheEviction ¶
func (s InspectorSnapshot) CacheEviction() uint64
CacheEviction reports observed cache evictions. Unbounded Local caches do not evict entries, so this compatibility counter remains zero.
func (InspectorSnapshot) CacheExpansion ¶
func (s InspectorSnapshot) CacheExpansion() uint64
CacheExpansion reports observed adaptive cache capacity expansions. Local caches no longer have fixed capacities, so this compatibility counter remains zero.
func (InspectorSnapshot) CacheHit ¶
func (s InspectorSnapshot) CacheHit() uint64
CacheHit reports observed cache hits.
func (InspectorSnapshot) CacheMiss ¶
func (s InspectorSnapshot) CacheMiss() uint64
CacheMiss reports observed cache misses.
func (InspectorSnapshot) CandidateCheck ¶
func (s InspectorSnapshot) CandidateCheck() uint64
CandidateCheck reports observed direct internal-ID membership checks.
func (InspectorSnapshot) DistinctValueCount ¶
func (s InspectorSnapshot) DistinctValueCount() (uint64, bool)
DistinctValueCount reports indexed concrete values, excluding wildcards.
func (InspectorSnapshot) EmptyResult ¶
func (s InspectorSnapshot) EmptyResult() uint64
EmptyResult reports observed empty results.
func (InspectorSnapshot) EntryCount ¶
func (s InspectorSnapshot) EntryCount() uint64
EntryCount reports the number of input entries consumed by the build.
func (InspectorSnapshot) FalsePositiveRate ¶
func (s InspectorSnapshot) FalsePositiveRate() (float64, bool)
FalsePositiveRate reports an estimate when one is meaningful.
func (InspectorSnapshot) Granularity ¶
func (s InspectorSnapshot) Granularity() (uint64, bool)
Granularity reports the selected number of quantized key classes.
func (InspectorSnapshot) ItemCount ¶
func (s InspectorSnapshot) ItemCount() (uint64, bool)
ItemCount reports indexed wildcard and concrete posting items.
func (InspectorSnapshot) MemoryLimit ¶
func (s InspectorSnapshot) MemoryLimit() (uint64, bool)
MemoryLimit reports the effective representation byte limit after applying every ancestor policy limit.
func (InspectorSnapshot) MemoryUsage ¶
func (s InspectorSnapshot) MemoryUsage() (uint64, bool)
MemoryUsage reports deterministic accounted representation bytes.
func (InspectorSnapshot) Mode ¶
func (s InspectorSnapshot) Mode() RuleMode
Mode reports the compiled representation mode.
func (InspectorSnapshot) RangePruning ¶
func (s InspectorSnapshot) RangePruning() uint64
RangePruning reports observed early All exits proved by disjoint bitmap ID ranges.
func (InspectorSnapshot) ResultCardinality ¶
func (s InspectorSnapshot) ResultCardinality() Histogram
ResultCardinality reports the captured result-cardinality histogram.
func (InspectorSnapshot) RuleCount ¶
func (s InspectorSnapshot) RuleCount() uint64
RuleCount reports the number of unique external rule IDs in the build.
func (InspectorSnapshot) Strategy ¶
func (s InspectorSnapshot) Strategy() string
Strategy reports the compiled strategy.
type LossyOption ¶
type LossyOption interface {
// contains filtered or unexported methods
}
LossyOption configures a memory-bounded representation selected during Build. Implementations are sealed so new options can be added without weakening validation of a schema.
func MemoryLimit ¶
func MemoryLimit(bytes uint64) LossyOption
MemoryLimit sets the maximum accounted bytes retained by one Lossy rule.
type Operator ¶
type Operator uint8
Operator identifies a comparison stored in a CompareBy constraint. The comparison is written from the query's perspective: OperatorGTE means query >= stored.
type Rule ¶
type Rule[T any] interface { // contains filtered or unexported methods }
Rule describes how constraints and query values of T are matched. Construct rules with Include, Exclude, the ordered filters, Between, CompareBy, and All. Its implementation is sealed so an index can rely on all rule invariants.
func All ¶
All combines rules with logical AND: a stored constraint matches only when every child rule matches. All may be nested.
For example, to match both country and customer tier:
ruleix.All(
ruleix.Include(func(c Constraint) (string, bool) { return c.Country, true }),
ruleix.Include(func(c Constraint) (string, bool) { return c.Tier, true }),
)
func Between ¶
Between matches an interval fully covered by a stored interval: stored.from <= query.from AND query.until <= stored.until. Either missing stored bound is a wildcard for that side of the interval; a missing query bound matches only a stored wildcard on the same side.
For example, to find stored validity windows that cover a query window:
ruleix.Between(
func(c Constraint) (time.Time, bool) { return c.ValidFrom, true },
func(c Constraint) (time.Time, bool) { return c.ValidUntil, true },
time.Time.Compare,
)
func CompareBy ¶
func CompareBy[T any, V any]( value Getter[T, V], operator Getter[T, Operator], compare Compare[V], ) Rule[T]
CompareBy evaluates the operator stored in each inserted rule against the concrete value supplied to Search. The query-side operator is ignored. A missing stored value is a wildcard and its operator is not validated. Build returns an error when a non-wildcard rule has no operator or an unsupported operator.
For example, a stored value with OperatorGTE and value 5 matches a query whose value is 7:
ruleix.CompareBy(
func(c Constraint) (int, bool) { return c.Orders, true },
func(c Constraint) (ruleix.Operator, bool) { return c.Operator, true },
cmp.Compare[int],
)
func Exclude ¶
func Exclude[T any, V comparable](get Getter[T, V]) Rule[T]
Exclude indexes an optional forbidden value. ok == false means no forbidden value. A concrete match excludes the associated result ID even when another stored constraint with that ID matches.
For example, to reject rules whose forbidden channel equals the query channel:
ruleix.Exclude(func(c Constraint) (string, bool) { return c.ExcludedChannel, true })
func Greater ¶
Greater matches query > stored. A missing stored value is a wildcard.
For example, a stored order-count threshold of 5 matches a query count of 6:
ruleix.Greater(
func(c Constraint) (int, bool) { return c.OrderCountThreshold, true },
cmp.Compare[int],
)
func GreaterOrEqual ¶
GreaterOrEqual matches query >= stored. A missing stored value is a wildcard.
For example, a stored minimum total of 100 matches a query total of 150:
ruleix.GreaterOrEqual(
func(c Constraint) (int, bool) { return c.MinimumTotal, true },
cmp.Compare[int],
)
func Include ¶
func Include[T any, V comparable](get Getter[T, V]) Rule[T]
Include matches a query field when it equals the stored field. A missing stored value is a wildcard and matches every concrete query value; a missing query value matches only stored wildcards.
For example, to match a rule's optional country:
ruleix.Include(func(c Constraint) (string, bool) { return c.Country, true })
func Inspect ¶
Inspect decorates rule with an observational handle. It does not change the compiled search tree or matching semantics. Inspect panics for a nil inspector or rule. Attaching the same inspector more than once in one schema makes Build fail.
func Less ¶
Less matches query < stored. A missing stored value is a wildcard.
For example, a stored upper limit of 10 matches a query value of 9:
ruleix.Less(
func(c Constraint) (int, bool) { return c.UpperLimit, true },
cmp.Compare[int],
)
func LessOrEqual ¶
LessOrEqual matches query <= stored. A missing stored value is a wildcard.
For example, a stored maximum total of 200 matches a query total of 150:
ruleix.LessOrEqual(
func(c Constraint) (int, bool) { return c.MaximumTotal, true },
cmp.Compare[int],
)
Source Files
¶
- all.go
- all_empty_order.go
- all_empty_ranking.go
- all_execution.go
- all_planning.go
- batch_analysis.go
- batch_context.go
- batch_short.go
- batch_typed.go
- between.go
- between_cache_types.go
- between_compact.go
- between_small_bounds.go
- between_streaming.go
- bitmap_intern.go
- bitmap_pool.go
- build_finalize.go
- builder.go
- canonical_value.go
- compare_by.go
- compare_by_streaming.go
- eq.go
- equality_antonym.go
- equality_antonym_cache.go
- equality_api.go
- equality_cache.go
- equality_codec.go
- equality_hash.go
- equality_matcher.go
- equality_streaming.go
- execution_capabilities.go
- execution_cost.go
- index_search.go
- inspect.go
- inspect_runtime_metrics.go
- local_between_packed.go
- local_cache.go
- local_candidate_mask.go
- local_empty_keys.go
- local_empty_operand.go
- local_predicate_projection.go
- lossy.go
- lossy_levels.go
- lossy_policy.go
- lossy_streaming_adaptive.go
- lossy_streaming_leaf.go
- not.go
- operator.go
- ordered.go
- ordered_index.go
- ordered_index_lookup.go
- ordered_key.go
- ordered_rebuild.go
- ordered_streaming.go
- posting_rebuild.go
- quantized_equality.go
- rule.go
- search_batch.go
- search_materialization.go
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
between_and_gt
command
Package main demonstrates combining Between with a strict greater-than rule.
|
Package main demonstrates combining Between with a strict greater-than rule. |
|
local_search
command
Command local_search demonstrates a batch of related searches.
|
Command local_search demonstrates a batch of related searches. |
|
multiple_columns
command
Package main demonstrates matching rules across several independent columns.
|
Package main demonstrates matching rules across several independent columns. |