features

package
v0.17.0 Latest Latest
Warning

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

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

Documentation

Overview

Package features defines the public API for Diverge feature flag providers.

Index

Constants

View Source
const UnleashManagedOverridesAnnotation = "divergedev.com/unleash-managed-overrides"

UnleashManagedOverridesAnnotation records the comma-separated feature override keys managed by the last successful Unleash Provision reconcile so stale strategy cleanup only inspects removed overrides rather than scanning the entire Unleash project.

Variables

View Source
var (
	// ErrFlagsmithNotFound is returned when a requested Flagsmith resource does not exist (HTTP 404).
	ErrFlagsmithNotFound = errors.New("flagsmith resource not found")

	// ErrFlagsmithUnauthorized is returned when Flagsmith rejects authentication (HTTP 401 or 403).
	ErrFlagsmithUnauthorized = errors.New("flagsmith authentication failed: unauthorized")
)
View Source
var (
	// ErrUnleashNotFound is returned when a requested Unleash resource does not exist (HTTP 404).
	ErrUnleashNotFound = errors.New("unleash resource not found")

	// ErrUnleashUnauthorized is returned when Unleash rejects authentication (HTTP 401 or 403).
	ErrUnleashUnauthorized = errors.New("unleash authentication failed: unauthorized")
)
View Source
var ErrFliptNotFound = errors.New("flipt resource not found")

ErrFliptNotFound is returned when a requested Flipt resource is not found (HTTP 404).

View Source
var Providers = registry.New[FeatureProvider]("feature")

Providers is the registry of available FeatureProvider implementations.

Functions

func BuildFlagdJSON

func BuildFlagdJSON(overrides map[string]string, envName string) ([]byte, error)

BuildFlagdJSON converts key-value overrides into flagd JSON format. When envName is non-empty, JSONLogic targeting rules are generated so that the overrides only apply when diverge.environment matches the environment.

func ConfigMapName

func ConfigMapName(envName string) string

ConfigMapName returns the ConfigMap resource name for a given environment.

func FlagsmithIdentityName

func FlagsmithIdentityName(namespace, envName string) string

FlagsmithIdentityName generates an RFC 1123 compliant identity name scoped to the environment's namespace and name, incorporating a stable hash so environments with identical or long name prefixes remain distinct (capped at 63 chars).

func FliptNamespaceName

func FliptNamespaceName(envName string) string

FliptNamespaceName formats the ephemeral Flipt namespace name for a given environment.

func UnleashStrategyTitle added in v0.15.0

func UnleashStrategyTitle(namespace, envName string) string

UnleashStrategyTitle generates a deterministic RFC 1123 compliant strategy title scoped to the environment's namespace and name, capped at 63 characters.

Types

type ConfigMapProvider

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

ConfigMapProvider manages feature flag overrides as a Kubernetes ConfigMap formatted for flagd and OpenFeature.

func NewConfigMapProvider

func NewConfigMapProvider(c client.Client, scheme *runtime.Scheme, logger logr.Logger) *ConfigMapProvider

NewConfigMapProvider creates a new ConfigMapProvider.

func (*ConfigMapProvider) Provision

Provision creates or updates a ConfigMap holding feature flag configurations.

func (*ConfigMapProvider) Status

Status returns whether the feature ConfigMap is ready.

func (*ConfigMapProvider) Teardown

func (p *ConfigMapProvider) Teardown(ctx context.Context, env *v1alpha1.Environment) error

Teardown deletes the feature ConfigMap.

func (*ConfigMapProvider) Type

func (p *ConfigMapProvider) Type() string

Type returns "configmap".

type FeatureProvider

type FeatureProvider interface {
	// Type returns the provider type identifier (e.g. "configmap", "flipt", "flagsmith", "noop").
	Type() string

	// Provision configures or creates ephemeral feature rules for the preview environment.
	Provision(ctx context.Context, env *v1alpha1.Environment) (*FeatureResult, error)

	// Teardown cleans up ephemeral rules when the preview environment is destroyed.
	Teardown(ctx context.Context, env *v1alpha1.Environment) error

	// Status returns the current health or readiness of feature flag provisioning.
	Status(ctx context.Context, env *v1alpha1.Environment) (*FeatureStatus, error)
}

FeatureProvider manages feature flags and remote configuration for preview environments.

type FeatureResult

type FeatureResult struct {
	// ProviderType indicates the active provider.
	ProviderType string

	// ConfigMapName is the name of any ConfigMap created to store flag configurations.
	ConfigMapName string

	// EnvVars are environment variables to inject into preview pods.
	EnvVars map[string]string

	// Message is an informative description of the provisioned state.
	Message string
}

FeatureResult contains the outcome of a Provision call.

type FeatureStatus

type FeatureStatus struct {
	// Ready indicates whether feature flag rules are successfully provisioned.
	Ready bool

	// Message describes the current status or error.
	Message string
}

FeatureStatus represents the current state of feature management for an environment.

type FlagdDefinition

type FlagdDefinition struct {
	Flags map[string]FlagdFlag `json:"flags"`
}

FlagdDefinition represents the JSON structure expected by flagd / OpenFeature file providers.

type FlagdFlag

type FlagdFlag struct {
	State          string                 `json:"state"`
	Variants       map[string]interface{} `json:"variants"`
	DefaultVariant string                 `json:"defaultVariant"`
	Targeting      interface{}            `json:"targeting,omitempty"`
}

FlagdFlag represents a single flag rule in flagd format.

type FlagsmithClient

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

FlagsmithClient provides an HTTP client for Flagsmith's Edge and Core REST API.

func NewFlagsmithClient

func NewFlagsmithClient(baseURL, environmentKey, masterAPIKey string, customHTTPClient *http.Client) (*FlagsmithClient, error)

NewFlagsmithClient creates a new FlagsmithClient with validated URL and SSRF protections.

func (*FlagsmithClient) DeleteIdentity

func (c *FlagsmithClient) DeleteIdentity(ctx context.Context, identifier string) error

DeleteIdentity removes an ephemeral identity and its associated overrides from Flagsmith.

func (*FlagsmithClient) EnsureIdentityWithTraits

func (c *FlagsmithClient) EnsureIdentityWithTraits(ctx context.Context, identifier string, traits map[string]interface{}) (*FlagsmithIdentity, error)

EnsureIdentityWithTraits creates or updates an identity in Flagsmith with the provided traits.

func (*FlagsmithClient) HealthCheck

func (c *FlagsmithClient) HealthCheck(ctx context.Context) error

HealthCheck verifies connectivity and authorization to Flagsmith.

func (*FlagsmithClient) SetIdentityFeatureState

func (c *FlagsmithClient) SetIdentityFeatureState(ctx context.Context, identifier, featureName string, enabled bool, value interface{}) (*FlagsmithFeatureState, error)

SetIdentityFeatureState creates or updates a feature state override for an identity.

type FlagsmithFeature

type FlagsmithFeature struct {
	ID   int64  `json:"id,omitempty"`
	Name string `json:"name"`
	Type string `json:"type,omitempty"`
}

FlagsmithFeature represents feature flag metadata in Flagsmith.

type FlagsmithFeatureState

type FlagsmithFeatureState struct {
	ID                int64            `json:"id,omitempty"`
	Feature           FlagsmithFeature `json:"feature"`
	Enabled           bool             `json:"enabled"`
	FeatureStateValue interface{}      `json:"feature_state_value,omitempty"`
}

FlagsmithFeatureState represents the evaluated or overridden state of a flag.

type FlagsmithIdentity

type FlagsmithIdentity struct {
	ID         int64                   `json:"id,omitempty"`
	Identifier string                  `json:"identifier"`
	Traits     []FlagsmithTrait        `json:"traits,omitempty"`
	Flags      []FlagsmithFeatureState `json:"flags,omitempty"`
}

FlagsmithIdentity represents an identified user or preview session with traits and flag overrides.

type FlagsmithProvider

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

FlagsmithProvider implements FeatureProvider for Flagsmith feature flag management.

func NewFlagsmithProvider

func NewFlagsmithProvider(c client.Client, scheme *runtime.Scheme, logger logr.Logger) *FlagsmithProvider

NewFlagsmithProvider creates a new FlagsmithProvider.

func (*FlagsmithProvider) Provision

Provision sets up an isolated Flagsmith identity with traits and applies feature flag overrides.

func (*FlagsmithProvider) Status

Status returns readiness and connectivity of the Flagsmith provider.

func (*FlagsmithProvider) Teardown

func (p *FlagsmithProvider) Teardown(ctx context.Context, env *v1alpha1.Environment) error

Teardown cleans up the ephemeral Flagsmith identity.

func (*FlagsmithProvider) Type

func (p *FlagsmithProvider) Type() string

Type returns "flagsmith".

func (*FlagsmithProvider) WithHTTPClient

func (p *FlagsmithProvider) WithHTTPClient(httpClient *http.Client) *FlagsmithProvider

WithHTTPClient allows overriding the default HTTP client (primarily for testing).

type FlagsmithTrait

type FlagsmithTrait struct {
	TraitKey   string      `json:"trait_key"`
	TraitValue interface{} `json:"trait_value"`
}

FlagsmithTrait represents a trait key-value pair associated with an identity.

type FliptClient

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

FliptClient provides a lightweight HTTP client for interacting with Flipt's v1 REST API.

func NewFliptClient

func NewFliptClient(baseURL, token string, customHTTPClient *http.Client) (*FliptClient, error)

NewFliptClient creates a new FliptClient with a bounded HTTP timeout.

func (*FliptClient) CreateNamespace

func (c *FliptClient) CreateNamespace(ctx context.Context, key, name, description string) error

CreateNamespace idempotently creates a namespace in Flipt.

func (*FliptClient) CreateOrUpdateFlag

func (c *FliptClient) CreateOrUpdateFlag(ctx context.Context, namespaceKey, flagKey, flagType string, enabled bool, variantVal string) error

CreateOrUpdateFlag creates or updates a boolean or variant flag in a given Flipt namespace.

func (*FliptClient) DeleteNamespace

func (c *FliptClient) DeleteNamespace(ctx context.Context, key string) error

DeleteNamespace deletes a namespace from Flipt (idempotent; 404 is treated as success).

func (*FliptClient) GetNamespace

func (c *FliptClient) GetNamespace(ctx context.Context, key string) error

GetNamespace retrieves a namespace by key from Flipt.

type FliptProvider

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

FliptProvider implements FeatureProvider for Flipt feature flags management.

func NewFliptProvider

func NewFliptProvider(c client.Client, scheme *runtime.Scheme, logger logr.Logger) *FliptProvider

NewFliptProvider creates a new FliptProvider.

func (*FliptProvider) Provision

func (p *FliptProvider) Provision(ctx context.Context, env *v1alpha1.Environment) (*FeatureResult, error)

Provision sets up an isolated Flipt namespace for the environment and creates flag overrides.

func (*FliptProvider) Status

Status checks whether the Flipt namespace is provisioned and reachable.

func (*FliptProvider) Teardown

func (p *FliptProvider) Teardown(ctx context.Context, env *v1alpha1.Environment) error

Teardown deletes the ephemeral Flipt namespace and all contained flags atomically.

func (*FliptProvider) Type

func (p *FliptProvider) Type() string

Type returns "flipt".

func (*FliptProvider) WithHTTPClient

func (p *FliptProvider) WithHTTPClient(client *http.Client) *FliptProvider

WithHTTPClient allows overriding the default HTTP client (primarily for testing).

type NoopProvider

type NoopProvider struct{}

NoopProvider is a no-op implementation of FeatureProvider.

func (*NoopProvider) Provision

func (n *NoopProvider) Provision(ctx context.Context, env *v1alpha1.Environment) (*FeatureResult, error)

Provision performs no operations and reports ready.

func (*NoopProvider) Status

Status always reports ready.

func (*NoopProvider) Teardown

func (n *NoopProvider) Teardown(ctx context.Context, env *v1alpha1.Environment) error

Teardown performs no operations.

func (*NoopProvider) Type

func (n *NoopProvider) Type() string

Type returns "noop".

type UnleashClient

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

UnleashClient provides an HTTP client for the Unleash Admin REST API.

func NewUnleashClient

func NewUnleashClient(baseURL, projectID, environment, adminToken, clientToken string, customHTTPClient *http.Client) (*UnleashClient, error)

NewUnleashClient creates a new UnleashClient with validated URL and SSRF protections.

func (*UnleashClient) DeletePreviewStrategies added in v0.15.0

func (c *UnleashClient) DeletePreviewStrategies(ctx context.Context, strategyTitle string, featureNames []string) error

DeletePreviewStrategies deletes all strategies matching strategyTitle across the specified features (or all project features when empty) and cleans up any diverge.environment NOT_IN exclusion constraints added for that preview environment.

func (*UnleashClient) EnableFeatureInEnvironment added in v0.16.0

func (c *UnleashClient) EnableFeatureInEnvironment(ctx context.Context, featureName string) error

EnableFeatureInEnvironment enables a feature toggle in the configured Unleash environment.

func (*UnleashClient) EnsureFeature added in v0.15.0

func (c *UnleashClient) EnsureFeature(ctx context.Context, featureName string) (*UnleashFeature, error)

EnsureFeature ensures a feature toggle exists in the configured Unleash project.

func (*UnleashClient) HealthCheck

func (c *UnleashClient) HealthCheck(ctx context.Context) error

HealthCheck verifies connectivity and authorization to the Unleash instance.

func (*UnleashClient) ListProjectFeatures added in v0.15.0

func (c *UnleashClient) ListProjectFeatures(ctx context.Context) ([]string, error)

ListProjectFeatures lists feature names in the configured Unleash project.

func (*UnleashClient) ListStrategies added in v0.15.0

func (c *UnleashClient) ListStrategies(ctx context.Context, featureName string) ([]UnleashStrategy, error)

ListStrategies returns the strategies configured on a feature in the target Unleash environment.

func (*UnleashClient) UpsertPreviewStrategy added in v0.15.0

func (c *UnleashClient) UpsertPreviewStrategy(
	ctx context.Context,
	featureName, strategyTitle, previewEnvValue string,
	enabled bool,
	variantValue string,
) (*UnleashStrategy, error)

UpsertPreviewStrategy creates or updates an activation strategy constrained to diverge.environment IN [previewEnvValue]. When enabled is false, it also adds a diverge.environment NOT_IN [previewEnvValue] exclusion constraint to any other strategies on the feature so broader strategies cannot turn the flag on in the preview environment.

type UnleashConstraint added in v0.15.0

type UnleashConstraint struct {
	ContextName     string   `json:"contextName"`
	Operator        string   `json:"operator"`
	Values          []string `json:"values"`
	CaseInsensitive bool     `json:"caseInsensitive,omitempty"`
	Inverted        bool     `json:"inverted,omitempty"`
}

UnleashConstraint represents a context constraint on an Unleash activation strategy.

type UnleashFeature added in v0.15.0

type UnleashFeature struct {
	Name           string `json:"name"`
	Type           string `json:"type,omitempty"`
	Description    string `json:"description,omitempty"`
	ImpressionData bool   `json:"impressionData,omitempty"`
}

UnleashFeature represents feature flag metadata in Unleash.

type UnleashProvider

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

UnleashProvider implements FeatureProvider for Unleash feature management.

func NewUnleashProvider

func NewUnleashProvider(c client.Client, scheme *runtime.Scheme, logger logr.Logger) *UnleashProvider

NewUnleashProvider creates a new UnleashProvider.

func (*UnleashProvider) Provision

Provision configures Unleash feature toggles and preview-scoped activation strategies for the environment.

func (*UnleashProvider) Status

Status returns readiness and connectivity of the Unleash provider.

func (*UnleashProvider) Teardown

func (p *UnleashProvider) Teardown(ctx context.Context, env *v1alpha1.Environment) error

Teardown removes preview-scoped activation strategies from Unleash.

func (*UnleashProvider) Type

func (p *UnleashProvider) Type() string

Type returns "unleash".

func (*UnleashProvider) WithHTTPClient

func (p *UnleashProvider) WithHTTPClient(httpClient *http.Client) *UnleashProvider

WithHTTPClient allows overriding the default HTTP client (primarily for testing).

type UnleashStrategy added in v0.15.0

type UnleashStrategy struct {
	ID          string              `json:"id,omitempty"`
	Name        string              `json:"name"`
	Title       string              `json:"title,omitempty"`
	Disabled    bool                `json:"disabled"`
	SortOrder   int                 `json:"sortOrder"`
	Constraints []UnleashConstraint `json:"constraints,omitempty"`
	Parameters  map[string]string   `json:"parameters,omitempty"`
	Variants    []UnleashVariant    `json:"variants,omitempty"`
}

UnleashStrategy represents an activation strategy attached to an Unleash feature in an environment.

type UnleashVariant added in v0.15.0

type UnleashVariant struct {
	Name       string                 `json:"name"`
	Weight     int                    `json:"weight"`
	WeightType string                 `json:"weightType"`
	Stickiness string                 `json:"stickiness"`
	Payload    *UnleashVariantPayload `json:"payload,omitempty"`
}

UnleashVariant represents a strategy-level variant in Unleash.

type UnleashVariantPayload added in v0.15.0

type UnleashVariantPayload struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

UnleashVariantPayload represents the payload returned when an Unleash strategy variant matches.

Jump to

Keyboard shortcuts

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