flag

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 27 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	PercentageMultiplier = float64(1000)
)
View Source
const VariationSDKDefault string = "SdkDefault"

Variables

This section is empty.

Functions

func DateFromContextOrDefault

func DateFromContextOrDefault(ctx ffcontext.Context, defaultDate time.Time) time.Time

func EnrichContext

func EnrichContext(ctx ffcontext.Context, enrichment map[string]any) ffcontext.Context

EnrichContext returns the context seen with the enrichment merged in its custom attributes (see enrichedContext), or the context itself when there is nothing to merge. The context of the caller is never modified.

func MergeSetOfRules

func MergeSetOfRules(initialRules, updates []Rule) *[]Rule

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:"-"`
}

func (*Context) AddIntoEvaluationContextEnrichment

func (s *Context) AddIntoEvaluationContextEnrichment(key string, value any)

AddIntoEvaluationContextEnrichment adds a key and value to the evaluation context enrichment.

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        ErrorCode = "FLAG_NOT_FOUND"
	ErrorCodeParseError          ErrorCode = "PARSE_ERROR"
	ErrorCodeTypeMismatch        ErrorCode = "TYPE_MISMATCH"
	ErrorCodeGeneral             ErrorCode = "GENERAL"
	ErrorCodeInvalidContext      ErrorCode = "INVALID_CONTEXT"
	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" yaml:"start,omitempty" toml:"start,omitempty"`

	// End is the ending time of the experimentation
	End *time.Time `json:"end,omitempty" yaml:"end,omitempty" toml:"end,omitempty"`
}

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
}

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" yaml:"variations,omitempty" toml:"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" yaml:"targeting,omitempty" toml:"targeting,omitempty"`

	// BucketingKey defines a source for a dynamic targeting key
	BucketingKey *string `json:"bucketingKey,omitempty" yaml:"bucketingKey,omitempty" toml:"bucketingKey,omitempty"`

	// DefaultRule is the originalRule applied after checking that any other rules
	// matched the user.
	DefaultRule *Rule `json:"defaultRule,omitempty" yaml:"defaultRule,omitempty" toml:"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" yaml:"experimentation,omitempty" toml:"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" yaml:"scheduledRollout,omitempty" toml:"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" yaml:"trackEvents,omitempty" toml:"trackEvents,omitempty"`

	// Disable is true if the flag is disabled.
	Disable *bool `json:"disable,omitempty" yaml:"disable,omitempty" toml:"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" yaml:"version,omitempty" toml:"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" yaml:"metadata,omitempty" toml:"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

func (*InternalFlag) GetRules

func (f *InternalFlag) GetRules() []Rule

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) 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
const (
	NikunjyQueryFormat   QueryFormat = "nikunjy"
	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 ...
	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
	// 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" yaml:"experimentation,omitempty" toml:"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" yaml:"scheduled,omitempty" toml:"scheduled,omitempty"`
}

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 */

	// 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:"-" yaml:"-" toml:"-" jsonschema:"-"`
}

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

func (r *Rule) EvaluatePercentageRollout(key, flagName string) (string, error)

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) GetName

func (r *Rule) GetName() string

func (*Rule) GetPercentages

func (r *Rule) GetPercentages() map[string]float64

func (*Rule) GetProgressiveRollout

func (r *Rule) GetProgressiveRollout() ProgressiveRollout

func (*Rule) GetQuery

func (r *Rule) GetQuery() string

func (*Rule) GetQueryFormat

func (r *Rule) GetQueryFormat() QueryFormat

GetQueryFormat is returning the format used for the query.

func (*Rule) GetTrimmedQuery

func (r *Rule) GetTrimmedQuery() string

GetTrimmedQuery is removing the break lines and return.

func (*Rule) GetVariationResult

func (r *Rule) GetVariationResult() string

func (*Rule) IsDisable

func (r *Rule) IsDisable() bool

func (*Rule) IsDynamic

func (r *Rule) IsDynamic() bool

IsDynamic is a function that allows to know if the rule has a dynamic result or not.

func (*Rule) IsValid

func (r *Rule) IsValid(svc *Service, defaultRule bool, variations map[string]*any) error

IsValid is checking if the rule is valid.

func (*Rule) MergeRules

func (r *Rule) MergeRules(updatedRule Rule)

MergeRules is merging 2 rules. It is used when we have to update a rule in a scheduled rollout.

func (*Rule) RequiresBucketing

func (r *Rule) RequiresBucketing() bool

RequiresBucketing checks if this rule requires a bucketing key for evaluation.

type ScheduledStep

type ScheduledStep struct {
	InternalFlag `yaml:",inline"`

	Date *time.Time `yaml:"date,omitempty" json:"date,omitempty" toml:"date,omitempty"`
}

ScheduledStep is one change of the flag.

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.

func (*Service) Close

func (s *Service) Close()

Close releases the memoized queries and flags. The Service stays usable: it rebuilds what it needs on the next use.

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.

Jump to

Keyboard shortcuts

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