Documentation
¶
Overview ¶
Package provider loads feature-flags documents and serves evaluations from an in-memory snapshot. Two providers exist: env, which turns today's Helm FEATURE_* variables into a document, and appconfig, which polls AWS AppConfig in the background and falls back to env when AppConfig cannot be reached at boot.
IsEnabled and Evaluate only read the current snapshot, so they never wait on the network.
Index ¶
Examples ¶
Constants ¶
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AppConfigConfig ¶
type AppConfigConfig struct {
Application string
Environment string
FlagsProfile string
CatalogProfile string
// Region overrides the region from the AWS default config chain.
Region string
// PollInterval is how often AppConfig is polled; at least MinPollInterval.
PollInterval time.Duration
// BootTimeout bounds the first load in NewAppConfigProvider. When it
// fails, the provider starts on the env values and keeps polling.
BootTimeout time.Duration
// Fetcher replaces the Data API fetcher, e.g. with one that reads from
// the AppConfig Agent.
Fetcher Fetcher
}
AppConfigConfig configures the appconfig provider. Application and Environment are required; the rest have defaults.
type Config ¶
type Config struct {
ProviderType ProviderType
// ClientName is the service using the flags, used in logs.
ClientName string
// EnvPrefix is the prefix of the Helm flag variables, e.g. "FEATURE_".
// The env provider reads them, and the appconfig provider falls back to
// them at boot.
EnvPrefix string
// Registry holds the service's custom operators and resolvers. Every
// document version is compiled with it.
Registry *engine.Registry
// MeterProvider records the provider's and the engine's metrics. Nil
// uses the global OpenTelemetry meter provider.
MeterProvider metric.MeterProvider
}
Config selects and names a provider.
type DataAPI ¶
type DataAPI interface {
StartConfigurationSession(ctx context.Context, params *appconfigdata.StartConfigurationSessionInput, optFns ...func(*appconfigdata.Options)) (*appconfigdata.StartConfigurationSessionOutput, error)
GetLatestConfiguration(ctx context.Context, params *appconfigdata.GetLatestConfigurationInput, optFns ...func(*appconfigdata.Options)) (*appconfigdata.GetLatestConfigurationOutput, error)
}
DataAPI is the part of the AppConfig Data client the fetcher uses.
type DataAPIFetcher ¶
type DataAPIFetcher struct {
// contains filtered or unexported fields
}
DataAPIFetcher fetches profiles through the AppConfig Data API, keeping one configuration session per profile. Each poll token is used once; a failed call drops the session so the next Fetch starts a new one, which also recovers from tokens that expired after 24 hours.
func NewDataAPIFetcher ¶
func NewDataAPIFetcher(client DataAPI, application, environment string, pollIntervalSeconds int32) *DataAPIFetcher
NewDataAPIFetcher returns a fetcher for one AppConfig application and environment. pollIntervalSeconds is passed to AppConfig as the minimum poll interval; the caller must not poll a profile more often.
type Fetcher ¶
type Fetcher interface {
// Fetch returns the content and version of profile. When the content is
// unchanged since this fetcher's previous successful call for profile,
// it returns changed=false and no data.
Fetch(ctx context.Context, profile string) (data []byte, version string, changed bool, err error)
}
Fetcher fetches the latest deployed content of an AppConfig configuration profile. It is the only part of the appconfig provider that talks to AWS, so another transport (for example the AppConfig Agent on localhost) can replace the Data API without changing parsing, validation or evaluation.
type PollFailure ¶
type PollFailure string
PollFailure says why a poll did not produce a new snapshot.
const ( // PollFailureFetch: AppConfig could not be reached or returned an error. PollFailureFetch PollFailure = "fetch" // PollFailureInvalid: AppConfig returned a version that does not parse, // validate or compile; the previous snapshot is kept. PollFailureInvalid PollFailure = "invalid" )
type Provider ¶
type Provider interface {
// IsEnabled reports whether flag is on for the caller described by
// attrs. An unknown flag is off and returns an error.
IsEnabled(ctx context.Context, flag string, attrs engine.Attributes) (bool, error)
// Evaluate returns the decision for flag and the reason behind it.
Evaluate(ctx context.Context, flag string, attrs engine.Attributes) (engine.Decision, error)
// Snapshot describes the documents currently being served.
Snapshot() Snapshot
// Close stops background polling. Evaluations keep working on the last
// snapshot.
Close() error
}
Provider evaluates flags against the current snapshot.
func NewAppConfigProvider ¶
NewAppConfigProvider loads flags from AWS AppConfig and keeps them current by polling in the background. The first load waits at most BootTimeout; if AppConfig cannot be reached by then, the provider serves the env values (config.EnvPrefix) until a poll succeeds. Call Close to stop polling.
func NewEnvProvider ¶
NewEnvProvider serves flags from environment variables starting with config.EnvPrefix, as Phase 1 does: FEATURE_NEW_CASHIER=true becomes flag new_cashier, on for every caller. Any value other than "true" (any case) is off. The variables are read once.
func NewProvider ¶
NewProvider returns the provider selected by config.ProviderType. The appconfig provider takes an AppConfigConfig as providerConfig.
Example (AppConfig) ¶
The Helm values of a service set FEATUREFLAGS_* next to its FEATURE_* fallback values; the service maps them to the provider config.
package main
import (
"context"
"log"
"os"
"time"
"github.com/luckylanggam/tools-go-featureflags/engine"
"github.com/luckylanggam/tools-go-featureflags/provider"
)
func main() {
ctx := context.Background()
reg := engine.NewRegistry()
// reg.RegisterOperator / reg.RegisterResolver for the catalog's entries.
ff, err := provider.NewProvider(ctx,
provider.Config{
ProviderType: provider.ProviderType(os.Getenv("FEATUREFLAGS_PROVIDER")),
ClientName: "xtremepush-updater",
EnvPrefix: "FEATURE_",
Registry: reg,
},
provider.AppConfigConfig{
Application: os.Getenv("FEATUREFLAGS_APPCONFIG_APPLICATION"),
Environment: os.Getenv("FEATUREFLAGS_APPCONFIG_ENVIRONMENT"),
Region: os.Getenv("FEATUREFLAGS_APPCONFIG_REGION"),
})
if err != nil {
log.Fatal(err)
}
defer ff.Close()
d, err := ff.Evaluate(ctx, "xp_multi_tenant_routing", engine.Attributes{"site_id": "7"})
if err != nil {
log.Printf("feature flag: %v", err)
}
s := ff.Snapshot()
log.Printf("xp_multi_tenant_routing=%t reason=%s source=%s flags=%s age=%s",
d.Enabled, d.Reason, s.Source, s.FlagsVersion, time.Since(s.SyncedAt))
}
Output:
Example (Env) ¶
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/luckylanggam/tools-go-featureflags/provider"
)
func main() {
os.Setenv("EXAMPLE_FEATURE_NEW_CASHIER", "true")
defer os.Unsetenv("EXAMPLE_FEATURE_NEW_CASHIER")
ff, err := provider.NewProvider(context.Background(), provider.Config{
ProviderType: provider.Env,
ClientName: "cashier",
EnvPrefix: "EXAMPLE_FEATURE_",
})
if err != nil {
log.Fatal(err)
}
defer ff.Close()
on, err := ff.IsEnabled(context.Background(), "new_cashier", nil)
fmt.Println(on, err, ff.Snapshot().Source)
}
Output: true <nil> env
type ProviderType ¶
type ProviderType string
ProviderType selects where flags are loaded from.
const ( Env ProviderType = "env" AppConfig ProviderType = "appconfig" )
type Snapshot ¶
type Snapshot struct {
Source Source
FlagsVersion string
CatalogVersion string
LoadedAt time.Time
SyncedAt time.Time
}
Snapshot describes the documents being served. FlagsVersion and CatalogVersion are the AppConfig version labels, or a content hash when a version has no label. LoadedAt is when this snapshot was built; SyncedAt is when its source last confirmed it is current.
type Source ¶
type Source string
Source says where the snapshot being served came from.
const ( // SourceAppConfig: the last poll reached AppConfig and its documents // are being served. SourceAppConfig Source = "appconfig" // SourceCache: the last good AppConfig snapshot is being served because // later polls failed or returned an invalid version. SourceCache Source = "cache" // SourceEnv: the Helm env values are being served because AppConfig has // not been reached since boot, or the env provider is in use. SourceEnv Source = "env" )