Documentation
¶
Overview ¶
Package flagdef defines the flags, their rules and the queries used to resolve them.
Index ¶
- Constants
- Variables
- func CloneMetadata(metadata map[string]any) map[string]any
- func CloneValue(val any) any
- func DateFromContextOrDefault(ctx ffcontext.Context, defaultDate time.Time) time.Time
- func MergeSetOfRules(initialRules, updates []Rule) *[]Rule
- func SegmentID(value any) (string, bool)
- type Context
- type EnrichedContext
- type ErrorCode
- type ExperimentationRollout
- type Flag
- type InternalFlag
- func (f *InternalFlag) DeepCopy() *InternalFlag
- func (f *InternalFlag) GetBucketingKey() string
- func (f *InternalFlag) GetBucketingKeyValue(ctx ffcontext.Context) (string, error)
- func (f *InternalFlag) GetDefaultRule() *Rule
- func (f *InternalFlag) GetMetadata() map[string]any
- func (f *InternalFlag) GetRuleIndexByName(name string) *int
- func (f *InternalFlag) GetRules() []Rule
- func (f *InternalFlag) GetVariationValue(name string) any
- func (f *InternalFlag) GetVariations() map[string]*any
- func (f *InternalFlag) GetVersion() string
- func (f *InternalFlag) IsDisable() bool
- func (f *InternalFlag) IsTrackEvents() bool
- func (f *InternalFlag) IsValid(svc *Service) error
- func (f *InternalFlag) RequiresBucketing() bool
- func (f *InternalFlag) SegmentNames(svc *Service) []string
- func (f *InternalFlag) SegmentTerms(svc *Service) []segment.Term
- func (f *InternalFlag) UsesSegments(svc *Service) bool
- func (f *InternalFlag) Value(flagName string, evaluationCtx ffcontext.Context, flagContext Context) (any, ResolutionDetails)
- type ProgressiveRollout
- type ProgressiveRolloutStep
- type QueryFormat
- type ResolutionDetails
- type ResolutionReason
- type Rollout
- type Rule
- func (r *Rule) Evaluate(svc *Service, key string, ctx ffcontext.Context, flagName string, ...) (string, error)
- func (r *Rule) EvaluatePercentageRollout(key, flagName string) (string, error)
- func (r *Rule) EvaluateProgressiveRollout(key, flagName string, evaluationDate time.Time) (string, error)
- func (r *Rule) GetName() string
- func (r *Rule) GetPercentages() map[string]float64
- func (r *Rule) GetProgressiveRollout() ProgressiveRollout
- func (r *Rule) GetQuery() string
- func (r *Rule) GetQueryFormat() QueryFormat
- func (r *Rule) GetTrimmedQuery() string
- func (r *Rule) GetVariationResult() string
- func (r *Rule) IsDisable() bool
- func (r *Rule) IsDynamic() bool
- func (r *Rule) IsValid(svc *Service, defaultRule bool, variations map[string]*any) error
- func (r *Rule) MergeRules(updatedRule Rule)
- func (r *Rule) RequiresBucketing() bool
- type ScheduledStep
- type SegmentQueryError
- type Service
- type ServiceOption
Constants ¶
const ( // PercentageMultiplier is the factor that converts percentages into whole buckets. PercentageMultiplier = float64(1000) )
const VariationSDKDefault string = "SdkDefault"
VariationSDKDefault is the variation returned when the SDK default value is used.
Variables ¶
var ErrInvalidSegment = parser.ErrSegmentSyntax
ErrInvalidSegment is wrapped by the errors of a segment term that is not valid, in both query formats.
Functions ¶
func CloneMetadata ¶
CloneMetadata returns a deep copy of the metadata of a flag, nil for nil. The metadata a flag holds is the one of the cache, shared by every evaluation: a caller that wants to hand it out or to change it works on a copy.
func CloneValue ¶
CloneValue returns a deep copy of the objects and arrays of a variation value, the other values (immutable) are returned as they are. The value a flag returns is the one stored in the cache, shared by every evaluation.
func DateFromContextOrDefault ¶
DateFromContextOrDefault returns the current date of ctx, or defaultDate when ctx has none.
func MergeSetOfRules ¶
MergeSetOfRules is taking a collection of rules and merge it with the updates from a schedule steps. If you want to edit a rule this rule should have a name already to be able to target the updates to the right place.
Types ¶
type Context ¶
type Context struct {
// EvaluationContextEnrichment will be merged with the evaluation context sent during the evaluation.
// It is useful to add common attributes to all the evaluation, such as a server version, environment, ...
//
// All those fields will be included in the custom attributes of the evaluation context,
// if in the evaluation context you have a field with the same name, it will override the common one.
// Default: nil
EvaluationContextEnrichment map[string]any `json:"evaluationContextEnrichment,omitempty"`
// DefaultSdkValue is the default value of the SDK when calling the variation.
DefaultSdkValue any `json:"defaultSdkValue,omitempty"`
// Service owns the caches that evaluating the flag uses. A client creates one and passes it
// here for every evaluation, so that the evaluations share the parsed queries and nothing else
// does. It is required: InternalFlag.Value returns an error resolution when it is nil.
Service *Service `json:"-"`
// Segments answers the membership questions of the segment() terms of the rules. Without one, the lookups
// are not answered: a segment is not a member by default (unknown for a segment with OnErrorUnknown, then the
// rule does not match unless it says onError: match) and the evaluation reports segment.StatusNotConfigured.
// The provider is called from the evaluating goroutine.
Segments segment.Provider `json:"-"`
// SegmentCatalog (optional) is the catalog of the segments of this evaluation, in place of the one of the
// Service: the relay proxy has one for each flag set. Its static segments are answered from memory, with no call
// to Segments and no allocation. Nil means the catalog of the Service.
SegmentCatalog *segment.Catalog `json:"-"`
// RequestContext is the context of the request that is evaluated: the membership lookups honour its
// cancellation and deadline. Nil means context.Background().
//
//nolint:containedctx // Value has no context parameter: the context travels with the per-evaluation settings
RequestContext context.Context `json:"-"`
}
Context holds the per-evaluation settings of a flag: the context enrichment, the SDK default value and the Service that owns the evaluation caches.
func (*Context) AddIntoEvaluationContextEnrichment ¶
AddIntoEvaluationContextEnrichment adds a key and value to the evaluation context enrichment.
type EnrichedContext ¶
EnrichedContext is an evaluation context seen with the evaluation context enrichment merged in its custom attributes (the enrichment wins over the attributes with the same name). It is a copy-on-enrich view: the context of the caller is never modified, so it can safely be shared by concurrent evaluations.
func NewEnrichedContext ¶
func NewEnrichedContext(ctx ffcontext.Context, enrichment map[string]any) *EnrichedContext
NewEnrichedContext returns an EnrichedContext view of ctx with the enrichment merged in its custom attributes. The context of the caller is never modified.
func (*EnrichedContext) AddCustomAttribute ¶
func (e *EnrichedContext) AddCustomAttribute(name string, value any)
AddCustomAttribute adds the attribute to the enriched view only.
func (*EnrichedContext) ExtractGOFFProtectedFields ¶
func (e *EnrichedContext) ExtractGOFFProtectedFields() ffcontext.GoffContextSpecifics
ExtractGOFFProtectedFields reads the protected fields where the enrichment can have set them.
func (*EnrichedContext) GetCustom ¶
func (e *EnrichedContext) GetCustom() map[string]any
GetCustom returns the attributes of the context with the enrichment merged in.
func (*EnrichedContext) IsAnonymous ¶
func (e *EnrichedContext) IsAnonymous() bool
IsAnonymous is the merged "anonymous" attribute when the enrichment sets it (as it was when the enrichment was written in the context of the caller), the status of the context otherwise.
type ErrorCode ¶
type ErrorCode = string
ErrorCode is an enum following the open-feature specs about error code.
const ( // ErrorCodeProviderNotReady and the next codes are proposed in the open-feature specs. ErrorCodeProviderNotReady ErrorCode = "PROVIDER_NOT_READY" // ErrorCodeFlagNotFound is the error code returned when the flag does not exist. ErrorCodeFlagNotFound ErrorCode = "FLAG_NOT_FOUND" // ErrorCodeParseError is the error code returned when a flag cannot be parsed. ErrorCodeParseError ErrorCode = "PARSE_ERROR" // ErrorCodeTypeMismatch is the error code returned when a value does not have the expected type. ErrorCodeTypeMismatch ErrorCode = "TYPE_MISMATCH" // ErrorCodeGeneral is the error code returned for a general error. ErrorCodeGeneral ErrorCode = "GENERAL" // ErrorCodeInvalidContext is the error code returned when the evaluation context is invalid. ErrorCodeInvalidContext ErrorCode = "INVALID_CONTEXT" // ErrorCodeTargetingKeyMissing is the error code returned when the targeting key is missing. ErrorCodeTargetingKeyMissing ErrorCode = "TARGETING_KEY_MISSING" // ErrorFlagConfiguration is returned when we were not able to use the flag because of a misconfiguration. ErrorFlagConfiguration ErrorCode = "FLAG_CONFIG" )
type ExperimentationRollout ¶
type ExperimentationRollout struct {
// Start is the starting time of the experimentation
Start *time.Time `json:"start,omitempty" toml:"start,omitempty" yaml:"start,omitempty"`
// End is the ending time of the experimentation
End *time.Time `json:"end,omitempty" toml:"end,omitempty" yaml:"end,omitempty"`
}
ExperimentationRollout is the time window (Start and End) during which the experimentation of the flag runs. Outside this window the flag serves its default value.
type Flag ¶
type Flag interface {
// Value is returning the Value associate to the flag
Value(
flagName string,
evaluationContext ffcontext.Context,
flagContext Context,
) (any, ResolutionDetails)
// GetVersion is the getter for the field Version
// Default: 0.0
GetVersion() string
// IsTrackEvents is the getter of the field TrackEvents
// Default: true
IsTrackEvents() bool
// IsDisable is the getter for the field Disable
// Default: false
IsDisable() bool
// GetVariationValue return the value of variation from his name
GetVariationValue(name string) any
// GetMetadata return the metadata associated to the flag
GetMetadata() map[string]any
}
Flag is a feature flag that can be evaluated.
type InternalFlag ¶
type InternalFlag struct {
// Variations are all the variations available for this flag. You can have as many variation as needed.
Variations *map[string]*any `json:"variations,omitempty" toml:"variations,omitempty" yaml:"variations,omitempty"` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
// Rules is the list of Rule for this flag.
// This an optional field.
Rules *[]Rule `json:"targeting,omitempty" toml:"targeting,omitempty" yaml:"targeting,omitempty"`
// BucketingKey defines a source for a dynamic targeting key
BucketingKey *string `json:"bucketingKey,omitempty" toml:"bucketingKey,omitempty" yaml:"bucketingKey,omitempty"`
// DefaultRule is the originalRule applied after checking that any other rules
// matched the user.
DefaultRule *Rule `json:"defaultRule,omitempty" toml:"defaultRule,omitempty" yaml:"defaultRule,omitempty"`
// Experimentation is your struct to configure an experimentation, it will allow you to configure a start date and
// an end date for your flag.
// When the experimentation is not running, the flag will serve the default value.
Experimentation *ExperimentationRollout `json:"experimentation,omitempty" toml:"experimentation,omitempty" yaml:"experimentation,omitempty"` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
// Scheduled is your struct to configure an update on some fields of your flag over time.
// You can add several steps that updates the flag, this is typically used if you want to gradually add more user
// in your flag.
Scheduled *[]ScheduledStep `json:"scheduledRollout,omitempty" toml:"scheduledRollout,omitempty" yaml:"scheduledRollout,omitempty"` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
// TrackEvents is false if you don't want to export the data in your data exporter.
// Default value is true
TrackEvents *bool `json:"trackEvents,omitempty" toml:"trackEvents,omitempty" yaml:"trackEvents,omitempty"`
// Disable is true if the flag is disabled.
Disable *bool `json:"disable,omitempty" toml:"disable,omitempty" yaml:"disable,omitempty"`
// Version (optional) This field contains the version of the flag.
// The version is manually managed when you configure your flags, and it is used to display the information
// in the notifications and data collection.
Version *string `json:"version,omitempty" toml:"version,omitempty" yaml:"version,omitempty"`
// Metadata is a field containing information about your flag such as an issue tracker link, a description, etc ...
Metadata *map[string]any `json:"metadata,omitempty" toml:"metadata,omitempty" yaml:"metadata,omitempty"`
}
InternalFlag is the internal representation of a flag when using semaphore. All the flags in your configuration files can have different format but will be converted into an InternalFlag to be used in the library.
func (*InternalFlag) DeepCopy ¶
func (f *InternalFlag) DeepCopy() *InternalFlag
DeepCopy returns a copy of the flag that shares no mutable data with it: the variations (and the values they hold), the rules, the rollouts, the scheduled steps and the metadata are copied, so changing the copy never changes the original.
func (*InternalFlag) GetBucketingKey ¶
func (f *InternalFlag) GetBucketingKey() string
GetBucketingKey return the name of the custom bucketing key if we are using one.
func (*InternalFlag) GetBucketingKeyValue ¶
func (f *InternalFlag) GetBucketingKeyValue(ctx ffcontext.Context) (string, error)
GetBucketingKeyValue return the value of the bucketing key from the context If requiresBucketing is false, it allows empty keys for flags that don't need them.
func (*InternalFlag) GetDefaultRule ¶
func (f *InternalFlag) GetDefaultRule() *Rule
GetDefaultRule is the getter of the field DefaultRule.
func (*InternalFlag) GetMetadata ¶
func (f *InternalFlag) GetMetadata() map[string]any
GetMetadata return the metadata associated to the flag.
func (*InternalFlag) GetRuleIndexByName ¶
func (f *InternalFlag) GetRuleIndexByName(name string) *int
GetRuleIndexByName returns the index of the rule with the given name, or nil if there is none.
func (*InternalFlag) GetRules ¶
func (f *InternalFlag) GetRules() []Rule
GetRules returns the rules of the flag.
func (*InternalFlag) GetVariationValue ¶
func (f *InternalFlag) GetVariationValue(name string) any
GetVariationValue return the value of variation from his name.
func (*InternalFlag) GetVariations ¶
func (f *InternalFlag) GetVariations() map[string]*any
GetVariations is the getter of the field Variations.
func (*InternalFlag) GetVersion ¶
func (f *InternalFlag) GetVersion() string
GetVersion is the getter for the field Version.
func (*InternalFlag) IsDisable ¶
func (f *InternalFlag) IsDisable() bool
IsDisable is the getter for the field Disable.
func (*InternalFlag) IsTrackEvents ¶
func (f *InternalFlag) IsTrackEvents() bool
IsTrackEvents is the getter of the field TrackEvents.
func (*InternalFlag) IsValid ¶
func (f *InternalFlag) IsValid(svc *Service) error
IsValid is checking if the current flag is valid. Validating a flag also keeps the cached parses of its nikunjy queries until its rules are garbage collected, so validating the flags of a configuration load is what keeps their queries cached across reloads.
func (*InternalFlag) RequiresBucketing ¶
func (f *InternalFlag) RequiresBucketing() bool
RequiresBucketing checks if the flag requires a bucketing key for evaluation A flag requires bucketing if it has percentage-based rules or progressive rollouts, including those introduced by scheduled rollout steps.
func (*InternalFlag) SegmentNames ¶
func (f *InternalFlag) SegmentNames(svc *Service) []string
SegmentNames returns the sorted names of the segments that the targeting rules of the flag use, including the rules that its scheduled steps add. It parses the queries: call it when a flag is loaded, not for each evaluation.
func (*InternalFlag) SegmentTerms ¶
func (f *InternalFlag) SegmentTerms(svc *Service) []segment.Term
SegmentTerms returns the distinct segment terms (segment name and attribute path) that the targeting rules of the flag use, including the rules that its scheduled steps add, sorted by segment then attribute. A relay can look them up for a request before it evaluates the flag. It parses the queries: call it when a flag is loaded, not for each evaluation.
func (*InternalFlag) UsesSegments ¶
func (f *InternalFlag) UsesSegments(svc *Service) bool
UsesSegments reports whether a targeting rule of the flag uses a segment.
func (*InternalFlag) Value ¶
func (f *InternalFlag) Value( flagName string, evaluationCtx ffcontext.Context, flagContext Context, ) (any, ResolutionDetails)
Value is returning the Value associate to the flag.
type ProgressiveRollout ¶
type ProgressiveRollout struct {
// Initial contains a description of the initial state of the rollout.
Initial *ProgressiveRolloutStep `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 164-byte string literal not displayed */
// End contains what describes the end status of the rollout.
End *ProgressiveRolloutStep `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 148-byte string literal not displayed */
}
ProgressiveRollout represents how to progressively roll out a originalRule.
type ProgressiveRolloutStep ¶
type ProgressiveRolloutStep struct {
// Variation - name of the variation for this step
Variation *string `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 162-byte string literal not displayed */
// Percentage is the percentage (initial or end) for the progressive rollout
Percentage *float64 `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 195-byte string literal not displayed */
// Date is the time it starts or ends.
Date *time.Time `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 146-byte string literal not displayed */
}
ProgressiveRolloutStep define a progressive rollout step (initial and end).
type QueryFormat ¶
type QueryFormat = string
QueryFormat is the query language of the rules.
const ( // NikunjyQueryFormat is the query format of the Nikunjy query language. NikunjyQueryFormat QueryFormat = "nikunjy" // JSONLogicQueryFormat is the query format of JSON Logic queries. JSONLogicQueryFormat QueryFormat = "jsonlogic" )
type ResolutionDetails ¶
type ResolutionDetails struct {
// RuleIndex indicates which rules applied
RuleIndex *int
// RuleName (optional) is the name of the associated rule if we have one
RuleName *string
// Metadata is a field containing information about your flag such as an issue tracker link, a description, etc ...
// It is nil when the flag has no metadata and the evaluation has no named rule: create a map before adding keys.
// It is never the map of the flag: the map belongs to the caller, who can add, change and delete keys in it
// (the cacheable keys of the OFREP responses are added so) without changing the flag or racing with the other
// evaluations. On the disabled and error paths, and for a scheduled flag, the nested objects and arrays are
// copies too; on the other paths they are the ones of the flag and must be treated as read-only.
Metadata map[string]any
// Variant indicates the name of the variant used when evaluating the flag
Variant string
// Reason indicates the reason of the decision
Reason ResolutionReason
// ErrorCode indicates the error code for this evaluation
ErrorCode ErrorCode
// ErrorMessage gives more information about the error
ErrorMessage string
// SegmentStatus is the health of the segment lookups of the evaluation, StatusNone when no rule looked a
// segment up. A value that depended on a segment lookup is never Cacheable.
SegmentStatus segment.Status
// Cacheable is set to true if an SDK/provider can cache the value locally.
Cacheable bool
}
ResolutionDetails is the object used to manipulate the data internally, it allows to retrieve the details of your evaluation.
type ResolutionReason ¶
type ResolutionReason = string
ResolutionReason is an enum following the open-feature specs about resolution reasons.
const ( // ReasonTargetingMatch The resolved value was the result of a dynamic evaluation, // such as a rule or specific user-targeting. // ex: serve variation A if username is Thomas ReasonTargetingMatch ResolutionReason = "TARGETING_MATCH" // ReasonTargetingMatchSplit The resolved value was the result of a dynamic evaluation, // that is serving a percentage. // ex: serve variation A to 10% of users with the username Thomas ReasonTargetingMatchSplit ResolutionReason = "TARGETING_MATCH_SPLIT" // ReasonSplit The resolved value was the result of pseudorandom assignment. // ex: serve variation A to 10% of all the users. ReasonSplit ResolutionReason = "SPLIT" // ReasonDisabled Indicates that the feature flag is disabled. ReasonDisabled ResolutionReason = "DISABLED" // ReasonDefault The resolved value was the result of the flag being disabled in the management system. ReasonDefault ResolutionReason = "DEFAULT" // ReasonStatic indicates that the feature flag evaluated to a // static value, for example, the default value for the flag // // Note: Typically means that no dynamic evaluation has been // executed for the feature flag. ReasonStatic ResolutionReason = "STATIC" // ReasonUnknown Indicates an unknown issue occurred during evaluation. ReasonUnknown ResolutionReason = "UNKNOWN" // ReasonError Indicates that an error occurred during evaluation // Note: The `errorCode`-field contains the details of this error. ReasonError ResolutionReason = "ERROR" // ReasonOffline Indicates that Semaphore is currently evaluating in offline mode. ReasonOffline ResolutionReason = "OFFLINE" )
type Rollout ¶
type Rollout struct {
// Experimentation is your struct to configure an experimentation, it will allow you to configure a start date and
// an end date for your flag.
// When the experimentation is not running, the flag will serve the default value.
Experimentation *ExperimentationRollout `json:"experimentation,omitempty" toml:"experimentation,omitempty" yaml:"experimentation,omitempty"` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
// Scheduled is your struct to configure an update on some fields of your flag over time.
// You can add several steps that update the flag, this is typically used if you want to gradually add more user
// in your flag.
Scheduled *[]ScheduledStep `json:"scheduled,omitempty" toml:"scheduled,omitempty" yaml:"scheduled,omitempty"`
}
Rollout groups the time-based rollout settings of a flag: an experimentation window, scheduled updates and a progressive rollout.
type Rule ¶
type Rule struct {
// Name is the name of the rule, this field is mandatory if you want
// to update the rule during scheduled rollout
Name *string `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 212-byte string literal not displayed */
// Query represents the query used to target the audience of the flag.
Query *string `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 217-byte string literal not displayed */
// VariationResult represents the variation name to use if the rule apply for the user.
// In case we have a percentage field in the config VariationResult is ignored
VariationResult *string `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 250-byte string literal not displayed */
// Percentages represents the percentage we should give to each variation.
// example: variationA = 10%, variationB = 80%, variationC = 10%
Percentages *map[string]float64 `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 185-byte string literal not displayed */
// ProgressiveRollout is your struct to configure a progressive rollout deployment of your flag.
// It will allow you to ramp up the percentage of your flag over time.
// You can decide at which percentage you starts with and at what percentage you ends with in your release ramp.
// Before the start date we will serve the initial percentage and, after we will serve the end percentage.
ProgressiveRollout *ProgressiveRollout `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 214-byte string literal not displayed */
// Disable indicates that this rule is disabled.
Disable *bool `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 151-byte string literal not displayed */
// OnError says what the rule does when its result depends on a segment() term whose membership is unknown
// (the store is down, ...): "skip" (the default) does not match the rule, "match" matches it, for the rules that
// deny. It has no effect on a rule without segment() terms.
OnError *string `` //nolint:lll // struct tags (json, yaml, toml, jsonschema, mapstructure) can not be wrapped
/* 303-byte string literal not displayed */
// QueryHash is the hash of Query that InternalFlag.IsValid computes once, when the flag is
// loaded, to find the evaluator of the query without hashing it for every evaluation.
// It is derived data: it is never read from or written to a configuration. It is exported
// only because the notifier compares flags with cmp.Equal, which rejects unexported
// fields; flags with the same queries have the same hash, so it does not make flags differ.
QueryHash uint64 `json:"-" jsonschema:"-" toml:"-" yaml:"-"`
}
Rule represents a rule applied by the flag.
func (*Rule) Evaluate ¶
func (r *Rule) Evaluate(svc *Service, key string, ctx ffcontext.Context, flagName string, isDefault bool, ) (string, error)
Evaluate is checking if the rule applies to for the user. If yes, it returns the variation you should use for this rule. The queries are parsed and cached by svc, which is required.
func (*Rule) EvaluatePercentageRollout ¶
EvaluatePercentageRollout is evaluating the percentage rollout for the rule.
The hash modulus is the legacy one: the raw percentages are summed, then scaled and truncated. Changing it would move users who already have a variation. The sum used to be done in map iteration order, and float addition is not associative, so it was not deterministic for 3 variations or more; it is now done in the bucket order. A hash that is beyond the end of the last bucket (the modulus can be one above it because of float rounding) gets the last variation that has a share, instead of an error.
func (*Rule) EvaluateProgressiveRollout ¶
func (r *Rule) EvaluateProgressiveRollout( key, flagName string, evaluationDate time.Time, ) (string, error)
EvaluateProgressiveRollout is evaluating the progressive rollout for the rule.
func (*Rule) GetPercentages ¶
GetPercentages returns the percentage of each variation in the rule.
func (*Rule) GetProgressiveRollout ¶
func (r *Rule) GetProgressiveRollout() ProgressiveRollout
GetProgressiveRollout returns the progressive rollout configuration of the rule.
func (*Rule) GetQueryFormat ¶
func (r *Rule) GetQueryFormat() QueryFormat
GetQueryFormat is returning the format used for the query.
func (*Rule) GetTrimmedQuery ¶
GetTrimmedQuery returns the query to compile: a rules-format query is joined on one line, a JsonLogic query is returned as written, because joining its lines would merge its tokens.
func (*Rule) GetVariationResult ¶
GetVariationResult returns the variation returned when the rule matches.
func (*Rule) IsDynamic ¶
IsDynamic is a function that allows to know if the rule has a dynamic result or not.
func (*Rule) MergeRules ¶
MergeRules is merging 2 rules. It is used when we have to update a rule in a scheduled rollout.
func (*Rule) RequiresBucketing ¶
RequiresBucketing checks if this rule requires a bucketing key for evaluation.
type ScheduledStep ¶
type ScheduledStep struct {
InternalFlag `yaml:",inline"`
Date *time.Time `json:"date,omitempty" toml:"date,omitempty" yaml:"date,omitempty"`
}
ScheduledStep is one change of the flag.
type SegmentQueryError ¶
type SegmentQueryError struct {
// Path is the place of the problem in the query, such as $.and[1].or[0].
Path string
// Reason says what is wrong.
Reason string
}
SegmentQueryError is the error of an inSegment operation that is not valid. It wraps ErrInvalidSegment.
func (*SegmentQueryError) Error ¶
func (e *SegmentQueryError) Error() string
Error implements error.
func (*SegmentQueryError) Unwrap ¶
func (*SegmentQueryError) Unwrap() error
Unwrap returns ErrInvalidSegment.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service owns the state that evaluating and validating flags needs, so that no package-level variable holds it: the parsed nikunjy queries, the memo of the scheduled rollouts, the compiled JsonLogic queries and the pool of the query context maps.
A client creates one Service and hands it to everything that validates or evaluates its flags (the cache that validates the flags it loads, and the evaluations through Context.Service). Two Services never share state, so the clients of a process (e.g. the flag sets of the relay proxy) neither contend on each other nor evict each other's entries. A Service is safe for concurrent use. Its caches are released when it is garbage collected; Close releases them earlier.
func NewService ¶
func NewService(opts ...ServiceOption) *Service
NewService creates an empty Service.
type ServiceOption ¶
type ServiceOption func(*Service)
ServiceOption customizes the Service that NewService creates.
func WithLogger ¶
func WithLogger(logger *slog.Logger) ServiceOption
WithLogger sets the logger of the Service. Without it the Service does not log.
func WithSegments ¶
func WithSegments(catalog *segment.Catalog) ServiceOption
WithSegments sets the definitions of the segments that the rules of the flags can use. A rule that uses another segment is accepted, with a warning in the log, and the segment matches nobody.
Source Files
¶
- constant.go
- context.go
- doc.go
- enriched_context.go
- error_code.go
- flag.go
- internal_flag.go
- internal_flag_copy.go
- metadata_constructor.go
- query_compiled.go
- query_jsonlogic_cache.go
- query_nikunjy_cache.go
- resolution_detail.go
- resolution_reason.go
- rollout.go
- rollout_experimentation.go
- rollout_progressive.go
- rollout_scheduled.go
- rule.go
- rule_validation.go
- scheduled_memo.go
- segment_eval.go
- segment_jsonlogic.go
- segment_registry.go
- segment_validation.go
- service.go
- typed_load.go
- variation_selection.go