features

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	WildCardValue = "*"

	ConjunctionAnd = "AND"
	ConjunctionOr  = "OR"

	OperatorEquals             = "EQUALS"
	OperatorNotEquals          = "NOT_EQUALS"
	OperatorGreaterThan        = "GREATER_THAN"
	OperatorLessThan           = "LESS_THAN"
	OperatorGreaterThanOrEqual = "GREATER_THAN_OR_EQUAL"
	OperatorLessThanOrEqual    = "LESS_THAN_OR_EQUAL"
	OperatorIn                 = "IN"
	OperatorNotIn              = "NOT_IN"

	DatatypeString  = "STRING"
	DatatypeInteger = "INTEGER"
	DatatypeFloat   = "FLOAT"
	DatatypeBoolean = "BOOLEAN"

	FeatureSourceFile     FeatureSourceType = iota // when feature config is loaded from a file.
	FeatureSourceRawBytes                          // when feature config is provided as raw JSON content.

	FeatureContentFormatJson = 1
)

Variables

This section is empty.

Functions

func GetFeatureValue

func GetFeatureValue(featureKey string, opts EvaluationOptions) (interface{}, error)

GetFeatureValue determines the evaluated value for a given feature key based on the provided evaluation options.

It performs the following checks in order:

  1. Ensures feature config is initialized and feature exists
  2. Checks if the feature is enabled
  3. Verifies the current time is within the feature’s schedule (if defined)
  4. Checks whether the feature applies to the provided rollout context (platform, environment, region)
  5. Evaluates all rules (if defined) against the rule context

If all checks pass, a weighted variant is selected and returned. If any check fails, the default value for the feature is returned.

func Init

func Init(opts *InitOptions) error

Init initializes the feature flag engine by loading and validating the configuration.

It accepts an InitOptions struct that specifies the source of the configuration (either a file path or raw JSON). The initialization process performs the following steps:

  1. Validates the InitOptions.
  2. Reads the configuration from the specified source.
  3. Validates the config against the embedded JSON schema.
  4. Unmarshals the config into a strongly typed FeatureConfig object.
  5. Optionally initializes a file or remote watcher to monitor for updates.

Init is guarded by a mutex to ensure thread safety, and it can only be executed once; subsequent calls will return immediately without reinitialization.

Returns an error if:

  • The options are invalid.
  • Reading from the file source fails.
  • Schema validation fails.
  • JSON unmarshalling fails.

func ValidateFeatureConfig

func ValidateFeatureConfig(configJSON []byte, schemaJSON []byte) error

ValidateFeatureConfig validates the feature config JSON against the provided schema. It checks for the following:

  1. JSON schema validation
  2. Content validations for feature properties
  3. Validates the conditions, rollouts, and schedule
  4. Ensures that the total weight of variants sums to 100
  5. Ensures that the start time is before the end time

The function returns an error if any validation fails.

Types

type Attributes

type Attributes struct {
	Canary       bool     `json:"canary"`
	Platforms    []string `json:"platforms"`
	Environments []string `json:"environments"`
	Regions      []string `json:"regions"`
}

type Condition

type Condition struct {
	Key      string      `json:"key"`
	Operator string      `json:"operator"`
	Value    interface{} `json:"value"`
}

type EvaluationOptions

type EvaluationOptions struct {

	// Platform represents the platform context (e.g., "web", "mobile") from which
	// the evaluation is being made. This helps apply platform-specific rollouts.
	Platform string

	// Environment indicates the current deployment environment (e.g., "production", "staging").
	// It's used to evaluate rollout targeting based on environment.
	Environment string

	// Region indicates the geographical or logical region of the request (e.g., "us", "eu").
	// It helps evaluate region-specific rollout rules.
	Region string

	// EvaluationBucketKey is an optional identifier used to ensure deterministic bucketing during feature evaluation.
	//
	// If provided, the feature flag engine uses this ID (e.g., user ID, session ID, device ID) to calculate
	// a consistent hash-based bucket value. This ensures that the same entity (user/device/session) will
	// consistently receive the same variant across multiple evaluations, enabling reliable A/B testing,
	// canary rollouts, or gradual feature exposure.
	//
	// If EvaluationBucketKey is not provided, the engine falls back to random bucketing using a pseudo-random number generator.
	// This is useful for anonymous users or stateless scenarios but will not guarantee consistency across requests.
	EvaluationBucketKey string

	// RuleContext contains dynamic key-value pairs that represent runtime facts
	// about the user or request, such as "userTier", "userId", or "subscriptionLevel".
	// These are used to evaluate rule-based conditions within the feature definition.
	RuleContext map[string]interface{}
}

EvaluationOptions holds the runtime context used to evaluate feature flags. This struct is passed to the evaluation engine when checking if a feature is enabled or determining which variant to return.

type Feature

type Feature struct {
	Name         string      `json:"name"`
	Description  string      `json:"description"`
	Owner        string      `json:"owner"`
	Enabled      bool        `json:"enabled"`
	Schedule     *Schedule   `json:"schedule"`
	Datatype     string      `json:"datatype"`
	DefaultValue interface{} `json:"defaultValue"`
	Variants     []*Variant  `json:"variants"`
	Rules        *Rules      `json:"rules"`
	Rollouts     []*Rollout  `json:"rollouts"`
	Metadata     *Metadata   `json:"metadata"`
}

type FeatureConfig

type FeatureConfig struct {
	Version    string              `json:"version"`
	Attributes *Attributes         `json:"attributes"`
	Features   map[string]*Feature `json:"features"`
}

func GetFeatureConfigStore

func GetFeatureConfigStore() (*FeatureConfig, error)

GetFeatureConfigStore returns the currently loaded and validated feature configuration.

The returned configuration reflects the most recent state, either from initial load or a dynamic update. If Init has not been called successfully, this function returns an error.

Returns:

  • *FeatureConfig: the current feature configuration in memory.
  • error: if the configuration has not been initialized yet.

type FeatureSourceType

type FeatureSourceType uint8 // FeatureSourceType represents the source type of the feature config.

type InitOptions

type InitOptions struct {

	// SourceType determines the origin of the feature flag configuration.
	// Supported values are:
	//   - FeatureSourceFile: The configuration is read from a file on disk.
	//   - FeatureSourceRawBytes: The configuration is provided directly as a raw JSON string.
	SourceType FeatureSourceType

	// Input contains either the full JSON content (when SourceType is SourceRawBytes)
	// or the absolute/relative file path to the configuration file (when SourceType is SourceFile).
	Input string

	// EnableWatch indicates whether the watch functionality is enabled.
	// When set to true, the system will monitor and respond to changes in real-time.
	// When EnableWatch is true, the WatcherOptions field must be set to a valid watcher configuration.
	// This allows the system to automatically reload or update the feature flags
	EnableWatch bool

	// WatcherOptions represents the configuration options for the watcher component.
	// It allows customization of the behavior and settings of the watcher, which is
	// responsible for monitoring and responding to specific events or changes.
	//
	// Fields in WatcherOptions may include parameters such as polling intervals,
	// event filters, logging preferences, and other settings that influence how
	// the watcher operates.
	WatcherOptions *watcher.WatcherOptions
}

InitOptions defines the input parameters for initializing the feature flag system. It specifies the source of the configuration file (file path or raw string), along with the content or path based on the selected source type.

func (*InitOptions) IsValid

func (o *InitOptions) IsValid() error

IsValid validates the InitOptions struct to ensure that all required fields are properly set and contain valid values. It performs the following checks:

  1. Verifies that the SourceType field is one of the allowed feature source types. If the SourceType is not valid, an error is returned.

  2. If the SourceType is FeatureSourceFile, it checks whether the Input field points to a readable file. If the file is not readable, an error is returned.

  3. If the EnableWatch field is set to true, it ensures that the WatcherOptions field is not nil. If WatcherOptions is nil, an error is returned.

Returns an error if any of the validation checks fail, otherwise returns nil.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager owns one feature-config store and its watcher lifecycle.

func NewManager

func NewManager(opts *InitOptions) (*Manager, error)

func (*Manager) Close

func (m *Manager) Close()

func (*Manager) GetFeatureConfigStore

func (m *Manager) GetFeatureConfigStore() (*FeatureConfig, error)

type Metadata

type Metadata struct {
	CreatedAt string   `json:"createdAt"`
	Tags      []string `json:"tags"`
}

type Rollout

type Rollout struct {
	Platform    string  `json:"platform"`
	Environment string  `json:"environment"`
	Region      string  `json:"region"`
	Percentage  float64 `json:"percentage"`
}

type Rules

type Rules struct {
	Conjunction string       `json:"conjunction"`
	Conditions  []*Condition `json:"conditions"`
}

type Schedule

type Schedule struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

type Variant

type Variant struct {
	Name   string  `json:"name"`
	Weight float64 `json:"weight"`
	Label  string  `json:"label"`
}

Jump to

Keyboard shortcuts

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