ldmodel

package
v3.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2024 License: Apache-2.0 Imports: 10 Imported by: 9

Documentation

Overview

Package ldmodel contains the LaunchDarkly Go SDK feature flag data model.

These types contain the subset of feature flag and user segment data that is sent by LaunchDarkly to the SDK.

There is a defined JSON schema for these types that is used in communication between the SDK and LaunchDarkly services, which is also the JSON encoding used for storing flags/segments in a persistent data store. The JSON schema does not correspond exactly to the exported field structure of these types; the ldmodel package provides functions for explicitly converting the types to and from JSON. See DataModelSerialization for details.

Normal use of the Go SDK does not require referencing this package directly. It is used internally by the SDK, but is published and versioned separately so it can be used in other LaunchDarkly components without making the SDK versioning dependent on these internal APIs.

The bulk of the flag evaluation logic is in the main go-server-sdk-evaluation package, rather than in these data model types. However, in order to allow certain optimizations that could not be done from outside the package without exposing implementation details in the API, some of the logic (such as target and clause matching) is implemented here.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MarshalFeatureFlagToJSONWriter

func MarshalFeatureFlagToJSONWriter(item FeatureFlag, writer *jwriter.Writer)

MarshalFeatureFlagToJSONWriter attempts to convert a FeatureFlag to JSON using the jsonstream API. For details, see: https://github.com/launchdarkly/go-jsonstream/v3

func MarshalSegmentToJSONWriter

func MarshalSegmentToJSONWriter(item Segment, writer *jwriter.Writer)

MarshalSegmentToJSONWriter attempts to convert a Segment to JSON using the jsonstream API. For details, see: https://github.com/launchdarkly/go-jsonstream/v3

func PreprocessFlag

func PreprocessFlag(f *FeatureFlag)

PreprocessFlag precomputes internal data structures based on the flag configuration, to speed up evaluations.

This is called once after a flag is deserialized from JSON, or is created with ldbuilders. If you construct a flag by some other means, you should call PreprocessFlag exactly once before making it available to any other code. The method is not safe for concurrent access across goroutines.

func PreprocessSegment

func PreprocessSegment(s *Segment)

PreprocessSegment precomputes internal data structures based on the segment configuration, to speed up evaluations.

This is called once after a segment is deserialized from JSON, or is created with ldbuilders. If you construct a segment by some other means, you should call PreprocessSegment exactly once before making it available to any other code. The method is not safe for concurrent access across goroutines.

Types

type Clause

type Clause struct {
	// ContextKind is the context kind that this clause applies to.
	//
	// LaunchDarkly will normally always set this property, but if it is empty/omitted, it should be
	// treated as ldcontext.DefaultKind. An empty string value here represents the property being unset (so
	// it will be omitted in serialization).
	//
	// If the value of Attribute is "kind", then ContextKind is ignored because the nature of the context kind
	// test is described in a richer way by Operator and Values.
	ContextKind ldcontext.Kind
	// Attribute specifies the context attribute that is being tested.
	//
	// This is required for all Operator types except SegmentMatch. If Op is SegmentMatch then Attribute
	// is ignored (and will normally be an empty ldattr.Ref{}).
	//
	// If the context's value for this attribute is a JSON array, then the test specified in the Clause is
	// repeated for each value in the array until a match is found or there are no more values.
	Attribute ldattr.Ref
	// Op specifies the type of test to perform.
	Op Operator
	// Values is a list of values to be compared to the user attribute.
	//
	// This is interpreted as an OR: if the user attribute matches any of these values with the specified
	// operator, the Clause matches the user.
	//
	// In the special case where Op is OperatorSegmentMtach, there should only be a single Value, which
	// must be a string: the key of the user segment.
	//
	// If the user does not have a value for the specified attribute, the Values are ignored and the
	// Clause is always treated as a non-match.
	Values []ldvalue.Value
	// Negate is true if the specified Operator should be inverted.
	//
	// For instance, this would cause OperatorIn to mean "not equal" rather than "equal". Note that if no
	// tests are performed for this Clause because the user does not have a value for the specified
	// attribute, then Negate will not come into effect (the Clause will just be treated as a non-match).
	Negate bool
	// contains filtered or unexported fields
}

Clause describes an individual clause within a FlagRule or SegmentRule.

type ClientSideAvailability

type ClientSideAvailability struct {
	// UsingMobileKey indicates that this flag is available to clients using the mobile key for authorization
	// (includes most desktop and mobile clients).
	UsingMobileKey bool
	// UsingEnvironmentID indicates that this flag is available to clients using the environment id to identify an
	// environment (includes client-side javascript clients).
	UsingEnvironmentID bool
	// Explicit is true if, when serializing this flag, all of the ClientSideAvailability properties should
	// be included. If it is false, then an older schema is used in which this object is entirely omitted,
	// UsingEnvironmentID is stored in a deprecated property, and UsingMobileKey is assumed to be true.
	//
	// This field exists to ensure that flag representations remain consistent when sent and received
	// even though the clientSideAvailability property may not be present in the JSON data. It is false
	// if the flag was deserialized from an older JSON schema that did not include that property.
	//
	// Similarly, when deserializing a flag, if it used the older schema then Explicit will be false and
	// UsingMobileKey will be true.
	Explicit bool
}

ClientSideAvailability describes whether a flag is available to client-side SDKs.

This field can be used by a server-side client to determine whether to include an individual flag in bootstrapped set of flag data (see https://docs.launchdarkly.com/sdk/client-side/javascript#bootstrapping).

type DataModelSerialization

type DataModelSerialization interface {
	// MarshalFeatureFlag converts a FeatureFlag into its serialized encoding.
	MarshalFeatureFlag(item FeatureFlag) ([]byte, error)

	// MarshalSegment converts a Segment into its serialized encoding.
	MarshalSegment(item Segment) ([]byte, error)

	// UnmarshalFeatureFlag attempts to convert a FeatureFlag from its serialized encoding.
	UnmarshalFeatureFlag(data []byte) (FeatureFlag, error)

	// UnmarshalSegment attempts to convert a Segment from its serialized encoding.
	UnmarshalSegment(data []byte) (Segment, error)
}

DataModelSerialization is an abstraction of an encoding for SDK data model objects.

The ldmodel package defines a standard JSON schema for FeatureFlag and Segment. Currently, this is the only encoding that is used, so the only implementation of DataModelSerialization is the one provided by NewDataModelSerialization(), but the interface allows for the possibility that other encodings will be defined in the future.

There are also other ways to convert these types to and from the JSON encoding:

1. FeatureFlag and Segment define MarshalJSON and UnmarshalJSON methods so that they wil be correctly encoded or decoded if you call Go's standard json.Marshal or json.Unmarshal.

2. There are equivalent methods for encoding and decoding via the go-jsonstream API (https://pkg.go.dev/github.com/launchdarkly/go-jsonstream/v3). These are used internally by the SDK to avoid inefficiencies in json.Marshal and json.Unmarshal.

3. If the build tag "launchdarkly_easyjson" is set, FeatureFlag and Segment will also define MarshalEasyJSON and UnmarshalEasyJSON methods for interoperability with the easyjson library. For details, see the go-jsonstream documentation.

There is no separately defined encoding for lower-level data model types such as FlagRule, since there is no guarantee that those will always be represented as individual JSON objects in future versions of the schema. If you want to create a JSON representation of those data structures you must define your own type and copy values into it.

func NewJSONDataModelSerialization

func NewJSONDataModelSerialization() DataModelSerialization

NewJSONDataModelSerialization provides the default JSON encoding for SDK data model objects.

Always use this rather than relying on json.Marshal() and json.Unmarshal(). The data model structs are guaranteed to serialize and deserialize correctly with json.Marshal() and json.Unmarshal(), but JSONDataModelSerialization may be enhanced in the future to use a more efficient mechanism.

type EvaluatorAccessorMethods

type EvaluatorAccessorMethods struct{}

EvaluatorAccessorMethods contains functions that are used by the evaluation engine in the parent package to perform certain lookup operations on data model structs.

These are defined in the ldmodel package because they take advantage of the preprocessing behavior that is defined for these types, which populates additional data structures to speed up such lookups. Those data structures are implementation details of this package, so they are not exported. Instead, these methods provide a more abstract way for the evaluation engine to perform simple lookups regardless of whether the preprocessed data is available. (Normally preprocessed data is always available, because the preprocessing step is done every time we unmarshal data from JSON; but the evaluator must be able to work even if it receives inputs that were constructed in some other way.)

For efficiency, all of these methods expect structs to be passed by address rather than by value. They are guaranteed not to modify any fields.

Defining these as methods of EvaluatorAccessorMethods (accessed via the global variable EvaluatorAccessors), rather than simple functions or methods of other types, keeps this functionality clearly grouped together and allows data model types like FlagRule to be simple structs without methods.

var EvaluatorAccessors EvaluatorAccessorMethods //nolint:gochecknoglobals

EvaluatorAccessors is the global entry point for EvaluatorAccessorMethods.

func (EvaluatorAccessorMethods) ClauseFindValue

func (e EvaluatorAccessorMethods) ClauseFindValue(clause *Clause, contextValue ldvalue.Value) bool

ClauseFindValue returns true if the specified value is deeply equal to any of the Clause's Values, or false otherwise. It also returns false if the value is a JSON array, a JSON object, or a JSON null (since equality tests are not valid for these in the LaunchDarkly model), or if the clause parameter is nil.

If preprocessing has been done, this is a fast map lookup (as long as the Clause's operator is "in", which is the only case where it makes sense to create a map). Otherwise it iterates the list.

func (EvaluatorAccessorMethods) ClauseGetValueAsRegexp

func (e EvaluatorAccessorMethods) ClauseGetValueAsRegexp(clause *Clause, index int) *regexp.Regexp

ClauseGetValueAsRegexp returns one of the Clause's values as a Regexp, if the value is a string that represents a valid regular expression.

It returns nil if the value is not a string or is not valid as a regular expression; if the index is out of range; or if the clause parameter is nil.

If preprocessing has been done, this is a fast slice lookup. Otherwise it calls regexp.Compile.

func (EvaluatorAccessorMethods) ClauseGetValueAsSemanticVersion

func (e EvaluatorAccessorMethods) ClauseGetValueAsSemanticVersion(clause *Clause, index int) (semver.Version, bool)

ClauseGetValueAsSemanticVersion returns one of the Clause's values as a semver.Version, if the value is a string in the correct format. Any other type is invalid.

The second return value is true for success or false for failure. It also returns failure if the index is out of range, or if the clause parameter is nil.

If preprocessing has been done, this is a fast slice lookup. Otherwise it calls TypeConversions.ValueToSemanticVersion.

func (EvaluatorAccessorMethods) ClauseGetValueAsTimestamp

func (e EvaluatorAccessorMethods) ClauseGetValueAsTimestamp(clause *Clause, index int) (time.Time, bool)

ClauseGetValueAsTimestamp returns one of the Clause's values as a time.Time, if the value is a string or number in the correct format. Any other type is invalid.

The second return value is true for success or false for failure.. It also returns failure if the index is out of range, or if the clause parameter is nil.

If preprocessing has been done, this is a fast slice lookup. Otherwise it calls TypeConversions.ValueToTimestamp.

func (EvaluatorAccessorMethods) SegmentFindKeyInExcluded

func (e EvaluatorAccessorMethods) SegmentFindKeyInExcluded(segment *Segment, key string) bool

SegmentFindKeyInExcluded returns true if the specified key is in this Segment's Excluded list, or false otherwise. It also returns false if the segment parameter is nil.

If preprocessing has been done, this is a fast map lookup. Otherwise it iterates the list.

func (EvaluatorAccessorMethods) SegmentFindKeyInIncluded

func (e EvaluatorAccessorMethods) SegmentFindKeyInIncluded(segment *Segment, key string) bool

SegmentFindKeyInIncluded returns true if the specified key is in this Segment's Included list, or false otherwise. It also returns false if the segment parameter is nil.

If preprocessing has been done, this is a fast map lookup. Otherwise it iterates the list.

func (EvaluatorAccessorMethods) SegmentTargetFindKey

func (e EvaluatorAccessorMethods) SegmentTargetFindKey(target *SegmentTarget, key string) bool

SegmentTargetFindKey returns true if the specified key is in this SegmentTarget's Values list, or false otherwise. It also returns false if the target parameter is nil.

If preprocessing has been done, this is a fast map lookup. Otherwise it iterates the list.

func (EvaluatorAccessorMethods) TargetFindKey

func (e EvaluatorAccessorMethods) TargetFindKey(target *Target, key string) bool

TargetFindKey returns true if the specified key is in this Target's Values list, or false otherwise. It also returns false if the target parameter is nil.

If preprocessing has been done, this is a fast map lookup. Otherwise it iterates the list.

type FeatureFlag

type FeatureFlag struct {
	// Key is the unique string key of the feature flag.
	Key string
	// On is true if targeting is turned on for this flag.
	//
	// If On is false, the evaluator always uses OffVariation and ignores all other fields.
	On bool
	// Prerequisites is a list of feature flag conditions that are prerequisites for this flag.
	//
	// If any prerequisite is not met, the flag behaves as if targeting is turned off.
	Prerequisites []Prerequisite
	// Targets contains sets of individually targeted users for the default context kind (user).
	//
	// Targets take precedence over Rules: if a user is matched by any Target, the Rules are ignored.
	// Targets are ignored if targeting is turned off.
	Targets []Target
	// ContextTargets contains sets of individually targeted users for specific context kinds.
	//
	// Targets take precedence over Rules: if a user is matched by any Target, the Rules are ignored.
	// Targets are ignored if targeting is turned off.
	ContextTargets []Target
	// Rules is a list of rules that may match a user.
	//
	// If a user is matched by a Rule, all subsequent Rules in the list are skipped. Rules are ignored
	// if targeting is turned off.
	Rules []FlagRule
	// Fallthrough defines the flag's behavior if targeting is turned on but the user is not matched
	// by any Target or Rule.
	Fallthrough VariationOrRollout
	// OffVariation specifies the variation index to use if targeting is turned off.
	//
	// If this is undefined (ldvalue.OptionalInt{}), Evaluate returns undefined for the variation
	// index and ldvalue.Null() for the value.
	OffVariation ldvalue.OptionalInt
	// Variations is the list of all allowable variations for this flag. The variation index in a
	// Target or Rule is a zero-based index to this list.
	Variations []ldvalue.Value
	// ClientSideAvailability indicates whether a flag is available using each of the client-side
	// authentication methods.
	ClientSideAvailability ClientSideAvailability
	// Salt is a randomized value assigned to this flag when it is created.
	//
	// The hash function used for calculating percentage rollouts uses this as a salt to ensure that
	// rollouts are consistent within each flag but not predictable from one flag to another.
	Salt string
	// TrackEvents is used internally by the SDK analytics event system.
	//
	// This field is true if the current LaunchDarkly account has data export enabled, and has turned on
	// the "send detailed event information for this flag" option for this flag. This tells the SDK to
	// send full event data for each flag evaluation, rather than only aggregate data in a summary event.
	//
	// The go-server-sdk-evaluation package does not implement that behavior; it is only in the data
	// model for use by the SDK.
	TrackEvents bool
	// TrackEventsFallthrough is used internally by the SDK analytics event system.
	//
	// This field is true if the current LaunchDarkly account has experimentation enabled, has associated
	// this flag with an experiment, and has enabled "default rule" for the experiment. This tells the
	// SDK to send full event data for any evaluation where this flag had targeting turned on but the
	// user did not match any targets or rules.
	//
	// The go-server-sdk-evaluation package does not implement that behavior; it is only in the data
	// model for use by the SDK.
	TrackEventsFallthrough bool
	// DebugEventsUntilDate is used internally by the SDK analytics event system.
	//
	// This field is non-zero if debugging for this flag has been turned on temporarily in the
	// LaunchDarkly dashboard. Debugging always is for a limited time, so the field specifies a Unix
	// millisecond timestamp when this mode should expire. Until then, the SDK will send full event data
	// for each evaluation of this flag.
	//
	// The go-server-sdk-evaluation package does not implement that behavior; it is only in the data
	// model for use by the SDK.
	DebugEventsUntilDate ldtime.UnixMillisecondTime
	// Version is an integer that is incremented by LaunchDarkly every time the configuration of the flag is
	// changed.
	Version int
	// Deleted is true if this is not actually a feature flag but rather a placeholder (tombstone) for a
	// deleted flag. This is only relevant in data store implementations. The SDK does not evaluate
	// deleted flags.
	Deleted bool
	// Migration contains migration-related flag parameters. If this flag is
	// for migration purposes, this property is guaranteed to be set.
	Migration *MigrationFlagParameters
	// SamplingRatio controls the rate at which feature and debug events are emitted from the SDK for
	// this particular flag. If this value is not defined, it is assumed to be 1. Non-positive
	// values will disable emission entirely.
	//
	// LaunchDarkly may affect this flag to prevent poorly performing applications from adversely
	// affecting upstream service health.
	SamplingRatio ldvalue.OptionalInt
	// ExcludeFromSummaries determines whether or not this flag will be excluded from the event
	// summarization process.
	//
	// LaunchDarkly may affect this flag to prevent poorly performing applications from adversely
	// affecting upstream service health.
	ExcludeFromSummaries bool
}

FeatureFlag describes an individual feature flag.

The fields of this struct are exported for use by LaunchDarkly internal components. Application code should normally not reference FeatureFlag fields directly; flag data normally comes from LaunchDarkly SDK endpoints in JSON form and can be deserialized using the DataModelSerialization interface.

func UnmarshalFeatureFlagFromJSONReader

func UnmarshalFeatureFlagFromJSONReader(reader *jreader.Reader) FeatureFlag

UnmarshalFeatureFlagFromJSONReader attempts to convert a FeatureFlag from JSON using the jsonstream API. For details, see: https://github.com/launchdarkly/go-jsonstream/v3

func (FeatureFlag) MarshalJSON

func (f FeatureFlag) MarshalJSON() ([]byte, error)

MarshalJSON overrides the default json.Marshal behavior to provide the same marshalling behavior that is used by NewJSONDataModelSerialization().

func (*FeatureFlag) UnmarshalJSON

func (f *FeatureFlag) UnmarshalJSON(data []byte) error

UnmarshalJSON overrides the default json.Unmarshal behavior to provide the same unmarshalling behavior that is used by NewJSONDataModelSerialization().

type FlagRule

type FlagRule struct {
	// VariationRollout properties for a FlagRule define what variation to return if the user matches
	// this rule.
	VariationOrRollout
	// ID is a randomized identifier assigned to each rule when it is created.
	//
	// This is used to populate the RuleID property of ldreason.EvaluationReason.
	ID string
	// Clauses is a list of test conditions that make up the rule. These are ANDed: every Clause must
	// match in order for the FlagRule to match.
	Clauses []Clause
	// TrackEvents is used internally by the SDK analytics event system.
	//
	// This field is true if the current LaunchDarkly account has experimentation enabled, has associated
	// this flag with an experiment, and has enabled this rule for the experiment. This tells the SDK to
	// send full event data for any evaluation that matches this rule.
	//
	// The go-server-sdk-evaluation package does not implement that behavior; it is only in the data
	// model for use by the SDK.
	TrackEvents bool
}

FlagRule describes a single rule within a feature flag.

A rule consists of a set of ANDed matching conditions (Clause) for a user, along with either a fixed variation or a set of rollout percentages to use if the user matches all of the clauses.

type MigrationFlagParameters

type MigrationFlagParameters struct {
	// CheckRatio controls the rate at which consistency checks are performing during a
	// migration-influenced read or write operation. This value can be controlled through the
	// LaunchDarkly UI and propagated downstream to the SDKs.
	CheckRatio ldvalue.OptionalInt
}

MigrationFlagParameters are used to control flag-specific migration configuration.

type Operator

type Operator string

Operator describes an operator for a clause.

const (
	// OperatorIn matches a user value and clause value if the two values are equal (including their type).
	OperatorIn Operator = "in"
	// OperatorEndsWith matches a user value and clause value if they are both strings and the former ends with
	// the latter.
	OperatorEndsWith Operator = "endsWith"
	// OperatorStartsWith matches a user value and clause value if they are both strings and the former starts
	// with the latter.
	OperatorStartsWith Operator = "startsWith"
	// OperatorMatches matches a user value and clause value if they are both strings and the latter is a valid
	// regular expression that matches the former.
	OperatorMatches Operator = "matches"
	// OperatorContains matches a user value and clause value if they are both strings and the former contains
	// the latter.
	OperatorContains Operator = "contains"
	// OperatorLessThan matches a user value and clause value if they are both numbers and the former < the
	// latter.
	OperatorLessThan Operator = "lessThan"
	// OperatorLessThanOrEqual matches a user value and clause value if they are both numbers and the former
	// <= the latter.
	OperatorLessThanOrEqual Operator = "lessThanOrEqual"
	// OperatorGreaterThan matches a user value and clause value if they are both numbers and the former > the
	// latter.
	OperatorGreaterThan Operator = "greaterThan"
	// OperatorGreaterThanOrEqual matches a user value and clause value if they are both numbers and the former
	// >= the latter.
	OperatorGreaterThanOrEqual Operator = "greaterThanOrEqual"
	// OperatorBefore matches a user value and clause value if they are both timestamps and the former < the
	// latter.
	//
	// A valid timestamp is either a string in RFC3339/ISO8601 format, or a number which is treated as Unix
	// milliseconds.
	OperatorBefore Operator = "before"
	// OperatorAfter matches a user value and clause value if they are both timestamps and the former > the
	// latter.
	//
	// A valid timestamp is either a string in RFC3339/ISO8601 format, or a number which is treated as Unix
	// milliseconds.
	OperatorAfter Operator = "after"
	// OperatorSegmentMatch matches a user if the user is included in the user segment whose key is the clause
	// value.
	OperatorSegmentMatch Operator = "segmentMatch"
	// OperatorSemVerEqual matches a user value and clause value if they are both semantic versions and they
	// are equal.
	//
	// A semantic version is a string that either follows the Semantic Versions 2.0 spec, or is an abbreviated
	// version consisting of digits and optional periods in the form "m" (equivalent to m.0.0) or "m.n"
	// (equivalent to m.n.0).
	OperatorSemVerEqual Operator = "semVerEqual"
	// OperatorSemVerLessThan matches a user value and clause value if they are both semantic versions and the
	// former < the latter.
	//
	// A semantic version is a string that either follows the Semantic Versions 2.0 spec, or is an abbreviated
	// version consisting of digits and optional periods in the form "m" (equivalent to m.0.0) or "m.n"
	// (equivalent to m.n.0).
	OperatorSemVerLessThan Operator = "semVerLessThan"
	// OperatorSemVerGreaterThan matches a user value and clause value if they are both semantic versions and
	// the former > the latter.
	//
	// A semantic version is a string that either follows the Semantic Versions 2.0 spec, or is an abbreviated
	// version consisting of digits and optional periods in the form "m" (equivalent to m.0.0) or "m.n"
	// (equivalent to m.n.0).
	OperatorSemVerGreaterThan Operator = "semVerGreaterThan"
)

List of available operators

type Prerequisite

type Prerequisite struct {
	// Key is the unique key of the feature flag to be evaluated as a prerequisite.
	Key string
	// Variation is the index of the variation that the prerequisite flag must return in order for
	// the prerequisite condition to be met. If the prerequisite flag has targeting turned on, then
	// the condition is not met even if the flag's OffVariation matches this value. This is always a
	// real variation index; it cannot be undefined.
	Variation int
}

Prerequisite describes a requirement that another feature flag return a specific variation.

A prerequisite condition is met if the specified prerequisite flag has targeting turned on and returns the specified variation.

type Rollout

type Rollout struct {
	// Kind specifies whether this rollout is a simple percentage rollout or represents an experiment. Experiments have
	// different behaviour for tracking and variation bucketing.
	Kind RolloutKind
	// ContextKind is the context kind that this rollout will use to get any necessary context attributes.
	//
	// LaunchDarkly will normally always set this property, but if it is empty/omitted, it should be
	// treated as ldcontext.DefaultKind. An empty string value here represents the property being unset
	// (so it will be omitted in serialization).
	ContextKind ldcontext.Kind
	// Variations is a list of the variations in the percentage rollout and what percentage of users
	// to include in each.
	//
	// The Weight values of all elements in this list should add up to 100000 (100%). If they do not,
	// the last element in the list will behave as if it includes any leftover percentage (that is, if
	// the weights are [1000, 1000, 1000] they will be treated as if they were [1000, 1000, 98000]).
	Variations []WeightedVariation
	// BucketBy specifies which user attribute should be used to distinguish between users in a rollout.
	// This only works for simple rollouts; it is ignored for experiments.
	//
	// The default (when BucketBy is empty) is ldattr.KeyAttr, the user's primary key. If you wish to
	// treat users with different keys as the same for rollout purposes as long as they have the same
	// "country" attribute, you would set this to "country".
	//
	// Simple rollouts always take the user's "secondary key" attribute into account as well if the user
	// has one. Experiments ignore the secondary key.
	BucketBy ldattr.Ref
	// Seed, if present, specifies the seed for the hashing algorithm this rollout will use to bucket users, so that
	// rollouts with the same Seed will assign the same users to the same buckets.
	// If unspecified, the seed will default to a combination of the flag key and flag-level Salt.
	Seed ldvalue.OptionalInt
}

Rollout describes how users will be bucketed into variations during a percentage rollout.

func (Rollout) IsExperiment

func (r Rollout) IsExperiment() bool

IsExperiment returns whether this rollout represents an experiment.

type RolloutKind

type RolloutKind string

RolloutKind describes whether a rollout is a simple percentage rollout or represents an experiment. Experiments have different behaviour for tracking and variation bucketing.

const (
	// RolloutKindRollout represents a simple percentage rollout. This is the default rollout kind, and will be assumed if
	// not otherwise specified.
	RolloutKindRollout RolloutKind = "rollout"
	// RolloutKindExperiment represents an experiment. Experiments have different behaviour for tracking and variation
	// bucketing.
	RolloutKindExperiment RolloutKind = "experiment"
)

type Segment

type Segment struct {
	// Key is the unique key of the user segment.
	Key string
	// Included is a list of context keys that are always matched by this segment, for the default context kind
	// ("user"). Other context kinds are covered by IncludedContexts.
	Included []string
	// Excluded is a list of user keys that are never matched by this segment, unless the key is also in Included.
	Excluded []string
	// IncludedContexts contains sets of individually included contexts for specific context kinds.
	//
	// For backward compatibility, the targeting lists are divided up as follows: for the default kind ("user"),
	// we list the keys in Included, but for all other context kinds we use IncludedContexts.
	IncludedContexts []SegmentTarget
	// ExcludedContexts contains sets of individually excluded contexts for specific context kinds.
	//
	// For backward compatibility, the targeting lists are divided up as follows: for the default kind ("user"),
	// we list the keys in Excluded, but for all other context kinds we use ExcludedContexts.
	ExcludedContexts []SegmentTarget
	// Salt is a randomized value assigned to this segment when it is created.
	//
	// The hash function used for calculating percentage rollouts uses this as a salt to ensure that
	// rollouts are consistent within each segment but not predictable from one segment to another.
	Salt string
	// Rules is a list of rules that may match a context.
	//
	// If a context is matched by a Rule, all subsequent Rules in the list are skipped. Rules are ignored
	// if the context's key was matched by Included, Excluded, IncludedContexts, or ExcludedContexts.
	Rules []SegmentRule
	// Unbounded is true if this is a segment whose included/excluded key lists are stored separately and are not
	// limited in size.
	//
	// The name is historical: "unbounded segments" was an earlier name for the product feature that is currently
	// known as "Big Segments". If Unbounded is true, this is a Big Segment.
	Unbounded bool
	// UnboundedContextKind is the context kind associated with the included/excluded key lists if this segment
	// is a Big Segment. If it is empty, we assume ldcontext.DefaultKind. This field is ignored if Unbounded is
	// false.
	//
	// An empty string value here represents the property being unset (so it will be omitted in
	// serialization).
	UnboundedContextKind ldcontext.Kind
	// Version is an integer that is incremented by LaunchDarkly every time the configuration of the segment is
	// changed.
	Version int
	// Generation is an integer that indicates which set of big segment data is currently active for this segment
	// key. LaunchDarkly increments it if a segment is deleted and recreated. This value is only meaningful for big
	// segments. If this field is unset, it means the segment representation used an older schema so the generation
	// is unknown, in which case matching a big segment is not possible.
	Generation ldvalue.OptionalInt
	// Deleted is true if this is not actually a user segment but rather a placeholder (tombstone) for a
	// deleted segment. This is only relevant in data store implementations.
	Deleted bool
	// contains filtered or unexported fields
}

Segment describes a group of contexts based on context keys and/or matching rules.

func UnmarshalSegmentFromJSONReader

func UnmarshalSegmentFromJSONReader(reader *jreader.Reader) Segment

UnmarshalSegmentFromJSONReader attempts to convert a Segment from JSON using the jsonstream API. For details, see: https://github.com/launchdarkly/go-jsonstream/v3

func (Segment) MarshalJSON

func (s Segment) MarshalJSON() ([]byte, error)

MarshalJSON overrides the default json.Marshal behavior to provide the same marshalling behavior that is used by NewJSONDataModelSerialization().

func (*Segment) UnmarshalJSON

func (s *Segment) UnmarshalJSON(data []byte) error

UnmarshalJSON overrides the default json.Unmarshal behavior to provide the same unmarshalling behavior that is used by NewJSONDataModelSerialization().

type SegmentRule

type SegmentRule struct {
	// ID is a randomized identifier assigned to each rule when it is created.
	ID string
	// Clauses is a list of test conditions that make up the rule. These are ANDed: every Clause must
	// match in order for the SegmentRule to match.
	Clauses []Clause
	// Weight, if defined, specifies a percentage rollout in which only a subset of contexts matching this
	// rule are included in the segment. This is specified as an integer from 0 (0%) to 100000 (100%).
	Weight ldvalue.OptionalInt
	// BucketBy specifies which context attribute should be used to distinguish between contexts in a rollout.
	// This property is ignored if Weight is undefined.
	//
	// The default (when BucketBy is empty) is ldattr.KeyAttr, the context's primary key. If you wish to
	// treat contexts with different keys as the same for rollout purposes as long as they have the same
	// "country" attribute, you would set this to "country".
	//
	// Rollouts always take the context's "secondary key" attribute into account as well if there is one.
	//
	// An empty ldattr.Ref{} value here represents the property being unset (so it will be omitted in
	// serialization). That is different from setting it explicitly to "", which is an invalid attribute
	// reference.
	BucketBy ldattr.Ref
	// RolloutContextKind specifies what kind of context the key (or other attribute if BucketBy is set)
	// should be used to get attributes when computing a rollout. This property is ignored if Weight is
	// undefined. If unset, it defaults to ldcontext.DefaultKind.
	//
	// An empty string value here represents the property being unset (so it will be omitted in
	// serialization).
	RolloutContextKind ldcontext.Kind
}

SegmentRule describes a single rule within a segment.

type SegmentTarget

type SegmentTarget struct {
	// ContextKind is the context kind that this target list applies to.
	//
	// LaunchDarkly will normally always set this property, but if it is empty/omitted, it should be
	// treated as ldcontext.DefaultKind. An empty string value here represents the property being unset
	// (so it will be omitted in serialization).
	ContextKind ldcontext.Kind
	// Values is the set of context keys included in this Target.
	Values []string
	// contains filtered or unexported fields
}

SegmentTarget describes a target list within a segment, for a specific context kind.

type Target

type Target struct {
	// ContextKind is the context kind that this target list applies to.
	//
	// LaunchDarkly will normally always set this property, but if it is empty/omitted, it should be
	// treated as ldcontext.DefaultKind. An empty string value here represents the property being unset (so
	// it will be omitted in serialization).
	ContextKind ldcontext.Kind
	// Values is the set of user keys included in this Target.
	Values []string
	// Variation is the index of the variation to be returned if the user matches one of these keys. This
	// is always a real variation index; it cannot be undefined.
	Variation int
	// contains filtered or unexported fields
}

Target describes a set of users who will receive a specific variation.

type TypeConversionMethods

type TypeConversionMethods struct{}

TypeConversionMethods contains type conversion functions that are used by the evaluation engine in the parent package. They implement the defined behavior for JSON value types when used with LaunchDarkly feature flag operators that apply to a more specialized logical type, such as timestamps and semantic versions.

These are defined in the ldmodel package, rather than in the parent package with the evaluation engine, for two reasons:

1. They are logically part of the LaunchDarkly data model. For instance, when a clause uses a date/time operator, that implies that the clause values must be strings or numbers in the specific format that LaunchDarkly uses for timestamps.

2. The preprocessing logic in ldmodel uses the same conversions to parse clause values as the appropriate types ahead of time. EvaluatorAccessorMethods will use the pre-parsed values if available, or else apply the conversions on the fly.

var TypeConversions TypeConversionMethods //nolint:gochecknoglobals

TypeConversions is the global entry point for TypeConversionMethods.

func (TypeConversionMethods) ValueToSemanticVersion

func (e TypeConversionMethods) ValueToSemanticVersion(value ldvalue.Value) (semver.Version, bool)

ValueToSemanticVersion attempts to convert a JSON value to a semver.Version.

If the value is a string, it is parsed with the parser defined in the semver package. Any other type is invalid.

The second return value is true for success or false for failure.

func (TypeConversionMethods) ValueToTimestamp

func (e TypeConversionMethods) ValueToTimestamp(value ldvalue.Value) (time.Time, bool)

ValueToTimestamp attempts to convert a JSON value to a time.Time, using the standard LaunchDarkly rules for timestamp values.

If the value is a string, it is parsed according to RFC3339. If the value is a number, it is treated as integer epoch milliseconds. Any other type is invalid.

The second return value is true for success or false for failure.

type VariationOrRollout

type VariationOrRollout struct {
	// Variation specifies the index of the variation to return. It is undefined (ldvalue.OptionalInt{})
	// if no specific variation is defined.
	Variation ldvalue.OptionalInt
	// Rollout specifies a percentage rollout to be used instead of a specific variation. A rollout is
	// only defined if it has a non-empty Variations list.
	Rollout Rollout
}

VariationOrRollout desscribes either a fixed variation or a percentage rollout.

There is a VariationOrRollout for every FlagRule, and also one in FeatureFlag.Fallthrough which is used if no rules match.

Invariant: one of the variation or rollout must be non-nil.

type WeightedVariation

type WeightedVariation struct {
	// Variation is the index of the variation to be returned if the user is in this bucket. This is
	// always a real variation index; it cannot be undefined.
	Variation int
	// Weight is the proportion of users who should go into this bucket, as an integer from 0 to 100000.
	Weight int
	// Untracked means that users allocated to this variation should not have tracking events sent.
	Untracked bool
}

WeightedVariation describes a fraction of users who will receive a specific variation.

Jump to

Keyboard shortcuts

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