refactor: centralize runtime feature flag bindings (#2142)
This commit is contained in:
@@ -9,35 +9,23 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
featureOfficeKey = "features.office"
|
||||
featureAppStatusBarKey = "features.appStatusBar"
|
||||
featureAuthKey = "features.auth"
|
||||
featureClaudeBackgroundPromptHandoffKey = "features.claudeBackgroundPromptHandoff"
|
||||
debugDevModeKey = "debug.devMode"
|
||||
envFeaturesOffice = "KANDEV_FEATURES_OFFICE"
|
||||
envFeaturesAppStatusBar = "KANDEV_FEATURES_APP_STATUS_BAR"
|
||||
envFeaturesAuth = "KANDEV_FEATURES_AUTH"
|
||||
envFeaturesClaudeBackgroundPromptHandoff = "KANDEV_FEATURES_CLAUDE_BACKGROUND_PROMPT_HANDOFF"
|
||||
envDebugDevMode = "KANDEV_DEBUG_DEV_MODE"
|
||||
envDebugPprofEnabled = "KANDEV_DEBUG_PPROF_ENABLED"
|
||||
envDebugAgentMessages = "KANDEV_DEBUG_AGENT_MESSAGES"
|
||||
envDebugPprofEnabled = "KANDEV_DEBUG_PPROF_ENABLED"
|
||||
envDebugAgentMessages = "KANDEV_DEBUG_AGENT_MESSAGES"
|
||||
)
|
||||
|
||||
func OptionsFromConfig(cfg *config.Config) Options {
|
||||
envValues := make(map[string]bool, len(registrations))
|
||||
for _, registration := range registrations {
|
||||
envValues[registration.definition.EnvVar] = isTruthy(os.Getenv(registration.definition.EnvVar))
|
||||
for _, impliedEnvVar := range registration.definition.ImpliedEnvVars {
|
||||
envValues[impliedEnvVar] = isTruthy(os.Getenv(impliedEnvVar))
|
||||
}
|
||||
}
|
||||
|
||||
return Options{
|
||||
DefaultValues: ValuesFromConfig(cfg),
|
||||
RuntimeValues: ValuesFromConfig(cfg),
|
||||
EnvValues: map[string]bool{
|
||||
envFeaturesOffice: isTruthy(os.Getenv(envFeaturesOffice)),
|
||||
envFeaturesAppStatusBar: isTruthy(os.Getenv(envFeaturesAppStatusBar)),
|
||||
envFeaturesAuth: isTruthy(os.Getenv(envFeaturesAuth)),
|
||||
envFeaturesClaudeBackgroundPromptHandoff: isTruthy(
|
||||
os.Getenv(envFeaturesClaudeBackgroundPromptHandoff),
|
||||
),
|
||||
envDebugDevMode: isTruthy(os.Getenv(envDebugDevMode)),
|
||||
envDebugPprofEnabled: isTruthy(os.Getenv(envDebugPprofEnabled)),
|
||||
envDebugAgentMessages: isTruthy(os.Getenv(envDebugAgentMessages)),
|
||||
},
|
||||
EnvValues: envValues,
|
||||
IsExplicitEnv: func(name string) bool {
|
||||
_, ok := os.LookupEnv(name)
|
||||
return ok && !profiles.WasApplied(name)
|
||||
@@ -46,41 +34,35 @@ func OptionsFromConfig(cfg *config.Config) Options {
|
||||
}
|
||||
|
||||
func ValuesFromConfig(cfg *config.Config) map[string]bool {
|
||||
debugEnabled := cfg.Debug.DevMode || cfg.Debug.PprofEnabled
|
||||
return map[string]bool{
|
||||
featureOfficeKey: cfg.Features.Office,
|
||||
featureAppStatusBarKey: cfg.Features.AppStatusBar,
|
||||
featureAuthKey: cfg.Features.Auth,
|
||||
featureClaudeBackgroundPromptHandoffKey: cfg.Features.ClaudeBackgroundPromptHandoff,
|
||||
debugDevModeKey: debugEnabled,
|
||||
values := make(map[string]bool, len(registrations))
|
||||
for _, registration := range registrations {
|
||||
values[registration.definition.Key] = registration.read(cfg)
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func ApplyStatesToConfig(cfg *config.Config, states []RuntimeFlagState) {
|
||||
for _, state := range states {
|
||||
switch state.Key {
|
||||
case featureOfficeKey:
|
||||
cfg.Features.Office = state.EffectiveValue
|
||||
case featureAppStatusBarKey:
|
||||
cfg.Features.AppStatusBar = state.EffectiveValue
|
||||
case featureAuthKey:
|
||||
cfg.Features.Auth = state.EffectiveValue
|
||||
case featureClaudeBackgroundPromptHandoffKey:
|
||||
cfg.Features.ClaudeBackgroundPromptHandoff = state.EffectiveValue
|
||||
case debugDevModeKey:
|
||||
cfg.Debug.DevMode = state.EffectiveValue
|
||||
cfg.Debug.PprofEnabled = state.EffectiveValue
|
||||
if state.EffectiveValue {
|
||||
setIfNotExplicit(envDebugAgentMessages, "true")
|
||||
setIfNotExplicit(envDebugPprofEnabled, "true")
|
||||
} else {
|
||||
unsetIfNotExplicit(envDebugAgentMessages)
|
||||
unsetIfNotExplicit(envDebugPprofEnabled)
|
||||
}
|
||||
registration, ok := registrationByKey(state.Key)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
registration.apply(cfg, state.EffectiveValue)
|
||||
}
|
||||
}
|
||||
|
||||
func applyDebugMode(cfg *config.Config, enabled bool) {
|
||||
cfg.Debug.DevMode = enabled
|
||||
cfg.Debug.PprofEnabled = enabled
|
||||
if enabled {
|
||||
setIfNotExplicit(envDebugAgentMessages, "true")
|
||||
setIfNotExplicit(envDebugPprofEnabled, "true")
|
||||
return
|
||||
}
|
||||
unsetIfNotExplicit(envDebugAgentMessages)
|
||||
unsetIfNotExplicit(envDebugPprofEnabled)
|
||||
}
|
||||
|
||||
func RuntimeOptionsFromAppliedConfig(defaults map[string]bool, cfg *config.Config) Options {
|
||||
opts := OptionsFromConfig(cfg)
|
||||
opts.DefaultValues = defaults
|
||||
|
||||
@@ -1,91 +1,150 @@
|
||||
package runtimeflags
|
||||
|
||||
var definitions = []RuntimeFlagDefinition{
|
||||
import "github.com/kandev/kandev/internal/common/config"
|
||||
|
||||
// runtimeFlagRegistration keeps the public metadata and the typed config
|
||||
// binding for a flag together. The function fields stay internal so the HTTP
|
||||
// registry response remains metadata-only.
|
||||
type runtimeFlagRegistration struct {
|
||||
definition RuntimeFlagDefinition
|
||||
read func(*config.Config) bool
|
||||
apply func(*config.Config, bool)
|
||||
}
|
||||
|
||||
type runtimeFlagIdentity struct {
|
||||
key string
|
||||
envVar string
|
||||
}
|
||||
|
||||
// retiredRuntimeFlagIdentities is append-only. When a flag graduates, remove
|
||||
// its active registration and move its identity here. Persisted overrides for
|
||||
// unknown keys are intentionally retained, so neither the key nor environment
|
||||
// variable may ever be reused for a different flag.
|
||||
var retiredRuntimeFlagIdentities = []runtimeFlagIdentity{
|
||||
{key: "features.plugins", envVar: "KANDEV_FEATURES_PLUGINS"},
|
||||
}
|
||||
|
||||
var registrations = []runtimeFlagRegistration{
|
||||
{
|
||||
Key: featureOfficeKey,
|
||||
EnvVar: envFeaturesOffice,
|
||||
Kind: KindFeature,
|
||||
Label: "Office mode",
|
||||
Description: "Enables autonomous agent office workflows and related settings.",
|
||||
Stability: StabilityExperimental,
|
||||
RiskLevel: RiskMedium,
|
||||
RiskDescription: "Office mode is still evolving. Workflows, routes, and background automation " +
|
||||
"may change between releases and should be reviewed before relying on them.",
|
||||
RestartRequired: true,
|
||||
Mutable: true,
|
||||
},
|
||||
{
|
||||
Key: featureAppStatusBarKey,
|
||||
EnvVar: envFeaturesAppStatusBar,
|
||||
Kind: KindFeature,
|
||||
Label: "App status bar",
|
||||
Description: "Adds the global connection, optional host metrics, and plugin status surface.",
|
||||
Stability: StabilityStable,
|
||||
RiskLevel: RiskLow,
|
||||
RiskDescription: "Changing this adds or removes the desktop and tablet status bar and the phone Status drawer entry " +
|
||||
"after restart. It does not stop connections, metrics collection requested by other clients, or plugins.",
|
||||
RestartRequired: true,
|
||||
Mutable: true,
|
||||
},
|
||||
{
|
||||
Key: featureAuthKey,
|
||||
EnvVar: envFeaturesAuth,
|
||||
Kind: KindFeature,
|
||||
Label: "Authentication & users",
|
||||
Description: "Requires every visitor to sign in and gives each user their own private workspaces. The first person to sign in after enabling becomes the admin.",
|
||||
Stability: StabilityExperimental,
|
||||
RiskLevel: RiskHigh,
|
||||
RiskDescription: "Turning this ON locks the instance behind a login after restart — the first visitor " +
|
||||
"completes a setup wizard and becomes the admin, and existing workspaces/secrets are assigned to " +
|
||||
"them. Turning it OFF after restart makes the instance open to anyone who can reach it again. " +
|
||||
"Enable it before exposing kandev on a shared or public network.",
|
||||
RestartRequired: true,
|
||||
Mutable: true,
|
||||
},
|
||||
{
|
||||
Key: featureClaudeBackgroundPromptHandoffKey,
|
||||
EnvVar: envFeaturesClaudeBackgroundPromptHandoff,
|
||||
Kind: KindFeature,
|
||||
Label: "Claude background prompt handoff",
|
||||
Description: "Allows Claude Code to accept a new prompt after its foreground yields while recognized background work remains active.",
|
||||
Stability: StabilityExperimental,
|
||||
RiskLevel: RiskHigh,
|
||||
RiskDescription: "Claude ACP background lifecycle signals can be missing, delayed, duplicated, or ambiguous. " +
|
||||
"Enabling this experiment can misclassify session activity or dispatch overlapping prompts. " +
|
||||
"Use it only for controlled testing and disable it if a session behaves unexpectedly.",
|
||||
RestartRequired: true,
|
||||
Mutable: true,
|
||||
},
|
||||
{
|
||||
Key: debugDevModeKey,
|
||||
EnvVar: envDebugDevMode,
|
||||
Kind: KindDebug,
|
||||
Label: "Debug mode",
|
||||
Description: "Enables local diagnostic endpoints and agent message debug logs for troubleshooting backend, agent, and tool-call behavior.",
|
||||
Stability: StabilityStable,
|
||||
RiskLevel: RiskHigh,
|
||||
RiskDescription: "Debug mode can expose local diagnostic endpoints and write prompt, file, " +
|
||||
"and tool-call content to local debug logs. Enable it only on trusted machines.",
|
||||
RestartRequired: true,
|
||||
Mutable: true,
|
||||
ImpliedEnvVars: []string{
|
||||
envDebugPprofEnabled,
|
||||
envDebugAgentMessages,
|
||||
definition: RuntimeFlagDefinition{
|
||||
Key: "features.office",
|
||||
EnvVar: "KANDEV_FEATURES_OFFICE",
|
||||
Kind: KindFeature,
|
||||
Label: "Office mode",
|
||||
Description: "Enables autonomous agent office workflows and related settings.",
|
||||
Stability: StabilityExperimental,
|
||||
RiskLevel: RiskMedium,
|
||||
RiskDescription: "Office mode is still evolving. Workflows, routes, and background automation " +
|
||||
"may change between releases and should be reviewed before relying on them.",
|
||||
RestartRequired: true,
|
||||
Mutable: true,
|
||||
},
|
||||
read: func(cfg *config.Config) bool { return cfg.Features.Office },
|
||||
apply: func(cfg *config.Config, value bool) { cfg.Features.Office = value },
|
||||
},
|
||||
{
|
||||
definition: RuntimeFlagDefinition{
|
||||
Key: "features.appStatusBar",
|
||||
EnvVar: "KANDEV_FEATURES_APP_STATUS_BAR",
|
||||
Kind: KindFeature,
|
||||
Label: "App status bar",
|
||||
Description: "Adds the global connection, optional host metrics, and plugin status surface.",
|
||||
Stability: StabilityStable,
|
||||
RiskLevel: RiskLow,
|
||||
RiskDescription: "Changing this adds or removes the desktop and tablet status bar and the phone Status drawer entry " +
|
||||
"after restart. It does not stop connections, metrics collection requested by other clients, or plugins.",
|
||||
RestartRequired: true,
|
||||
Mutable: true,
|
||||
},
|
||||
read: func(cfg *config.Config) bool { return cfg.Features.AppStatusBar },
|
||||
apply: func(cfg *config.Config, value bool) { cfg.Features.AppStatusBar = value },
|
||||
},
|
||||
{
|
||||
definition: RuntimeFlagDefinition{
|
||||
Key: "features.auth",
|
||||
EnvVar: "KANDEV_FEATURES_AUTH",
|
||||
Kind: KindFeature,
|
||||
Label: "Authentication & users",
|
||||
Description: "Requires every visitor to sign in and gives each user their own private workspaces. The first person to sign in after enabling becomes the admin.",
|
||||
Stability: StabilityExperimental,
|
||||
RiskLevel: RiskHigh,
|
||||
RiskDescription: "Turning this ON locks the instance behind a login after restart — the first visitor " +
|
||||
"completes a setup wizard and becomes the admin, and existing workspaces/secrets are assigned to " +
|
||||
"them. Turning it OFF after restart makes the instance open to anyone who can reach it again. " +
|
||||
"Enable it before exposing kandev on a shared or public network.",
|
||||
RestartRequired: true,
|
||||
Mutable: true,
|
||||
},
|
||||
read: func(cfg *config.Config) bool { return cfg.Features.Auth },
|
||||
apply: func(cfg *config.Config, value bool) { cfg.Features.Auth = value },
|
||||
},
|
||||
{
|
||||
definition: RuntimeFlagDefinition{
|
||||
Key: "features.claudeBackgroundPromptHandoff",
|
||||
EnvVar: "KANDEV_FEATURES_CLAUDE_BACKGROUND_PROMPT_HANDOFF",
|
||||
Kind: KindFeature,
|
||||
Label: "Claude background prompt handoff",
|
||||
Description: "Allows Claude Code to accept a new prompt after its foreground yields while recognized background work remains active.",
|
||||
Stability: StabilityExperimental,
|
||||
RiskLevel: RiskHigh,
|
||||
RiskDescription: "Claude ACP background lifecycle signals can be missing, delayed, duplicated, or ambiguous. " +
|
||||
"Enabling this experiment can misclassify session activity or dispatch overlapping prompts. " +
|
||||
"Use it only for controlled testing and disable it if a session behaves unexpectedly.",
|
||||
RestartRequired: true,
|
||||
Mutable: true,
|
||||
},
|
||||
read: func(cfg *config.Config) bool { return cfg.Features.ClaudeBackgroundPromptHandoff },
|
||||
apply: func(cfg *config.Config, value bool) { cfg.Features.ClaudeBackgroundPromptHandoff = value },
|
||||
},
|
||||
{
|
||||
definition: RuntimeFlagDefinition{
|
||||
Key: "debug.devMode",
|
||||
EnvVar: "KANDEV_DEBUG_DEV_MODE",
|
||||
Kind: KindDebug,
|
||||
Label: "Debug mode",
|
||||
Description: "Enables local diagnostic endpoints and agent message debug logs for troubleshooting backend, agent, and tool-call behavior.",
|
||||
Stability: StabilityStable,
|
||||
RiskLevel: RiskHigh,
|
||||
RiskDescription: "Debug mode can expose local diagnostic endpoints and write prompt, file, " +
|
||||
"and tool-call content to local debug logs. Enable it only on trusted machines.",
|
||||
RestartRequired: true,
|
||||
Mutable: true,
|
||||
ImpliedEnvVars: []string{
|
||||
envDebugPprofEnabled,
|
||||
envDebugAgentMessages,
|
||||
},
|
||||
},
|
||||
read: func(cfg *config.Config) bool { return cfg.Debug.DevMode || cfg.Debug.PprofEnabled },
|
||||
apply: applyDebugMode,
|
||||
},
|
||||
}
|
||||
|
||||
func Definitions() []RuntimeFlagDefinition {
|
||||
out := make([]RuntimeFlagDefinition, len(definitions))
|
||||
copy(out, definitions)
|
||||
out := make([]RuntimeFlagDefinition, len(registrations))
|
||||
for i, registration := range registrations {
|
||||
out[i] = publicDefinition(registration.definition)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func DefinitionByKey(key string) (RuntimeFlagDefinition, bool) {
|
||||
for _, def := range definitions {
|
||||
if def.Key == key {
|
||||
return def, true
|
||||
registration, ok := registrationByKey(key)
|
||||
if !ok {
|
||||
return RuntimeFlagDefinition{}, false
|
||||
}
|
||||
return publicDefinition(registration.definition), true
|
||||
}
|
||||
|
||||
func registrationByKey(key string) (runtimeFlagRegistration, bool) {
|
||||
for _, registration := range registrations {
|
||||
if registration.definition.Key == key {
|
||||
return registration, true
|
||||
}
|
||||
}
|
||||
return RuntimeFlagDefinition{}, false
|
||||
return runtimeFlagRegistration{}, false
|
||||
}
|
||||
|
||||
func publicDefinition(definition RuntimeFlagDefinition) RuntimeFlagDefinition {
|
||||
definition.ImpliedEnvVars = append([]string(nil), definition.ImpliedEnvVars...)
|
||||
return definition
|
||||
}
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
package runtimeflags
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/config"
|
||||
"github.com/kandev/kandev/internal/profiles"
|
||||
)
|
||||
|
||||
type featureFieldBinding struct {
|
||||
fieldIndex int
|
||||
fieldName string
|
||||
key string
|
||||
profileKey string
|
||||
envVar string
|
||||
}
|
||||
|
||||
func TestDefinitionsIncludeOfficeExperimentalMetadata(t *testing.T) {
|
||||
def, ok := DefinitionByKey("features.office")
|
||||
@@ -35,6 +50,15 @@ func TestDefinitionsExcludePlugins(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetiredRuntimeFlagIdentitiesIncludePlugins(t *testing.T) {
|
||||
for _, identity := range retiredRuntimeFlagIdentities {
|
||||
if identity.key == "features.plugins" && identity.envVar == "KANDEV_FEATURES_PLUGINS" {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("graduated plugins flag identity is missing from the retired identity set")
|
||||
}
|
||||
|
||||
func TestDefinitionsIncludeAppStatusBarMetadata(t *testing.T) {
|
||||
def, ok := DefinitionByKey("features.appStatusBar")
|
||||
if !ok {
|
||||
@@ -90,3 +114,289 @@ func TestDefinitionsExposeSingleUserFacingDebugToggle(t *testing.T) {
|
||||
t.Fatal("debug.agentMessages must not be a top-level user-facing toggle")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeFlagRegistrationsHaveCompleteMetadata(t *testing.T) {
|
||||
retiredKeys, retiredEnvVars := retiredIdentitySets(t)
|
||||
activeKeys := make(map[string]struct{}, len(registrations))
|
||||
activeEnvVars := make(map[string]string, len(registrations))
|
||||
|
||||
for _, registration := range registrations {
|
||||
definition := registration.definition
|
||||
validateRuntimeFlagDefinition(t, definition)
|
||||
if registration.read == nil || registration.apply == nil {
|
||||
t.Fatalf("runtime flag registration %q is missing a config binding", definition.Key)
|
||||
}
|
||||
if _, exists := activeKeys[definition.Key]; exists {
|
||||
t.Fatalf("duplicate runtime flag registration for %q", definition.Key)
|
||||
}
|
||||
activeKeys[definition.Key] = struct{}{}
|
||||
if _, retired := retiredKeys[definition.Key]; retired {
|
||||
t.Fatalf("active runtime flag %q reuses a retired key", definition.Key)
|
||||
}
|
||||
registerActiveEnvVar(t, activeEnvVars, retiredEnvVars, definition.Key, definition.EnvVar)
|
||||
for _, envVar := range definition.ImpliedEnvVars {
|
||||
registerActiveEnvVar(t, activeEnvVars, retiredEnvVars, definition.Key, envVar)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeFlagConfigBindingsAreIsolated(t *testing.T) {
|
||||
// Keep debug-mode's intentional environment side effects inert while this
|
||||
// test exercises only the typed config bindings.
|
||||
t.Setenv(envDebugAgentMessages, "explicit")
|
||||
t.Setenv(envDebugPprofEnabled, "explicit")
|
||||
|
||||
for _, target := range registrations {
|
||||
cfg := &config.Config{}
|
||||
target.apply(cfg, true)
|
||||
for _, registration := range registrations {
|
||||
want := registration.definition.Key == target.definition.Key
|
||||
if got := registration.read(cfg); got != want {
|
||||
t.Fatalf(
|
||||
"applying %q changed read value for %q to %t; want %t",
|
||||
target.definition.Key,
|
||||
registration.definition.Key,
|
||||
got,
|
||||
want,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
target.apply(cfg, false)
|
||||
for _, registration := range registrations {
|
||||
if registration.read(cfg) {
|
||||
t.Fatalf("disabling %q left %q enabled", target.definition.Key, registration.definition.Key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFeatureBindingsExactlyMatchConfigAndProfiles keeps the typed config,
|
||||
// profile defaults, and feature registry in lockstep in both directions.
|
||||
func TestFeatureBindingsExactlyMatchConfigAndProfiles(t *testing.T) {
|
||||
defaults, err := profiles.FeatureFlagDefaults()
|
||||
if err != nil {
|
||||
t.Fatalf("FeatureFlagDefaults: %v", err)
|
||||
}
|
||||
fields := featureFieldBindings(t)
|
||||
registered := registeredFeatureBindings(t)
|
||||
|
||||
for key, field := range fields {
|
||||
registration, ok := registered[key]
|
||||
if !ok {
|
||||
t.Fatalf("FeaturesConfig.%s has no runtime flag registration for %q", field.fieldName, key)
|
||||
}
|
||||
if registration.definition.EnvVar != field.envVar {
|
||||
t.Fatalf("FeaturesConfig.%s EnvVar = %q, want %q", field.fieldName, registration.definition.EnvVar, field.envVar)
|
||||
}
|
||||
if _, ok := defaults[field.profileKey]; !ok {
|
||||
t.Fatalf("FeaturesConfig.%s has no profile default for %q", field.fieldName, field.profileKey)
|
||||
}
|
||||
}
|
||||
for key := range registered {
|
||||
if _, ok := fields[key]; !ok {
|
||||
t.Fatalf("feature registration %q has no FeaturesConfig field", key)
|
||||
}
|
||||
}
|
||||
for profileKey := range defaults {
|
||||
if !hasProfileKey(fields, profileKey) {
|
||||
t.Fatalf("profile feature %q has no FeaturesConfig field", profileKey)
|
||||
}
|
||||
}
|
||||
if len(fields) != len(registered) || len(fields) != len(defaults) {
|
||||
t.Fatalf(
|
||||
"feature contract size mismatch: config=%d registry=%d profiles=%d",
|
||||
len(fields),
|
||||
len(registered),
|
||||
len(defaults),
|
||||
)
|
||||
}
|
||||
|
||||
assertFeatureConfigRoundTrips(t, fields)
|
||||
}
|
||||
|
||||
func retiredIdentitySets(t *testing.T) (map[string]struct{}, map[string]struct{}) {
|
||||
t.Helper()
|
||||
keys := make(map[string]struct{}, len(retiredRuntimeFlagIdentities))
|
||||
envVars := make(map[string]struct{}, len(retiredRuntimeFlagIdentities))
|
||||
for _, identity := range retiredRuntimeFlagIdentities {
|
||||
if strings.TrimSpace(identity.key) == "" || strings.TrimSpace(identity.envVar) == "" {
|
||||
t.Fatal("retired runtime flag identities must include both key and environment variable")
|
||||
}
|
||||
if _, exists := keys[identity.key]; exists {
|
||||
t.Fatalf("duplicate retired runtime flag key %q", identity.key)
|
||||
}
|
||||
keys[identity.key] = struct{}{}
|
||||
if _, exists := envVars[identity.envVar]; exists {
|
||||
t.Fatalf("duplicate retired runtime flag environment variable %q", identity.envVar)
|
||||
}
|
||||
envVars[identity.envVar] = struct{}{}
|
||||
}
|
||||
return keys, envVars
|
||||
}
|
||||
|
||||
func registerActiveEnvVar(
|
||||
t *testing.T,
|
||||
active map[string]string,
|
||||
retired map[string]struct{},
|
||||
key string,
|
||||
envVar string,
|
||||
) {
|
||||
t.Helper()
|
||||
if strings.TrimSpace(envVar) == "" {
|
||||
t.Fatalf("runtime flag %q has an empty environment variable", key)
|
||||
}
|
||||
if owner, exists := active[envVar]; exists {
|
||||
t.Fatalf("runtime flags %q and %q both use environment variable %q", owner, key, envVar)
|
||||
}
|
||||
if _, exists := retired[envVar]; exists {
|
||||
t.Fatalf("active runtime flag %q reuses retired environment variable %q", key, envVar)
|
||||
}
|
||||
active[envVar] = key
|
||||
}
|
||||
|
||||
func validateRuntimeFlagDefinition(t *testing.T, definition RuntimeFlagDefinition) {
|
||||
t.Helper()
|
||||
wantKeyPrefix, wantEnvPrefix := definitionPrefixes(t, definition.Kind)
|
||||
if !strings.HasPrefix(definition.Key, wantKeyPrefix) || len(definition.Key) == len(wantKeyPrefix) {
|
||||
t.Fatalf("runtime flag key %q must start with %q and include a name", definition.Key, wantKeyPrefix)
|
||||
}
|
||||
if !strings.HasPrefix(definition.EnvVar, wantEnvPrefix) || len(definition.EnvVar) == len(wantEnvPrefix) {
|
||||
t.Fatalf("runtime flag %q environment variable %q must start with %q", definition.Key, definition.EnvVar, wantEnvPrefix)
|
||||
}
|
||||
for name, value := range map[string]string{
|
||||
"label": definition.Label, "description": definition.Description, "risk description": definition.RiskDescription,
|
||||
} {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
t.Fatalf("runtime flag %q has an empty %s", definition.Key, name)
|
||||
}
|
||||
}
|
||||
if !validStability(definition.Stability) {
|
||||
t.Fatalf("runtime flag %q has invalid stability %q", definition.Key, definition.Stability)
|
||||
}
|
||||
if !validRiskLevel(definition.RiskLevel) {
|
||||
t.Fatalf("runtime flag %q has invalid risk level %q", definition.Key, definition.RiskLevel)
|
||||
}
|
||||
if !definition.RestartRequired {
|
||||
t.Fatalf("runtime flag %q must declare restart_required", definition.Key)
|
||||
}
|
||||
if !definition.Mutable {
|
||||
t.Fatalf("runtime flag %q must declare mutable", definition.Key)
|
||||
}
|
||||
}
|
||||
|
||||
func definitionPrefixes(t *testing.T, kind RuntimeFlagKind) (string, string) {
|
||||
t.Helper()
|
||||
switch kind {
|
||||
case KindFeature:
|
||||
return "features.", "KANDEV_FEATURES_"
|
||||
case KindDebug:
|
||||
return "debug.", "KANDEV_DEBUG_"
|
||||
default:
|
||||
t.Fatalf("invalid runtime flag kind %q", kind)
|
||||
return "", ""
|
||||
}
|
||||
}
|
||||
|
||||
func validStability(stability RuntimeFlagStability) bool {
|
||||
switch stability {
|
||||
case StabilityStable, StabilityBeta, StabilityExperimental:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func validRiskLevel(risk RuntimeFlagRiskLevel) bool {
|
||||
switch risk {
|
||||
case RiskLow, RiskMedium, RiskHigh:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func featureFieldBindings(t *testing.T) map[string]featureFieldBinding {
|
||||
t.Helper()
|
||||
typeOfFeatures := reflect.TypeOf(config.FeaturesConfig{})
|
||||
fields := make(map[string]featureFieldBinding, typeOfFeatures.NumField())
|
||||
for i := 0; i < typeOfFeatures.NumField(); i++ {
|
||||
field := typeOfFeatures.Field(i)
|
||||
if field.Type.Kind() != reflect.Bool {
|
||||
t.Fatalf("FeaturesConfig.%s has type %s; feature flags must be bool", field.Name, field.Type)
|
||||
}
|
||||
jsonName := requiredTagName(t, field, "json")
|
||||
profileKey := requiredTagName(t, field, "mapstructure")
|
||||
key := "features." + jsonName
|
||||
if _, exists := fields[key]; exists {
|
||||
t.Fatalf("duplicate FeaturesConfig JSON key %q", jsonName)
|
||||
}
|
||||
fields[key] = featureFieldBinding{
|
||||
fieldIndex: i,
|
||||
fieldName: field.Name,
|
||||
key: key,
|
||||
profileKey: profileKey,
|
||||
envVar: "KANDEV_FEATURES_" + strings.ToUpper(profileKey),
|
||||
}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
func requiredTagName(t *testing.T, field reflect.StructField, tag string) string {
|
||||
t.Helper()
|
||||
name := strings.Split(field.Tag.Get(tag), ",")[0]
|
||||
if name == "" || name == "-" {
|
||||
t.Fatalf("FeaturesConfig.%s is missing a %s name", field.Name, tag)
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func registeredFeatureBindings(t *testing.T) map[string]runtimeFlagRegistration {
|
||||
t.Helper()
|
||||
registered := make(map[string]runtimeFlagRegistration)
|
||||
for _, registration := range registrations {
|
||||
definition := registration.definition
|
||||
if definition.Kind != KindFeature && !strings.HasPrefix(definition.Key, "features.") {
|
||||
continue
|
||||
}
|
||||
if _, exists := registered[definition.Key]; exists {
|
||||
t.Fatalf("duplicate feature registration %q", definition.Key)
|
||||
}
|
||||
registered[definition.Key] = registration
|
||||
}
|
||||
return registered
|
||||
}
|
||||
|
||||
func hasProfileKey(fields map[string]featureFieldBinding, profileKey string) bool {
|
||||
for _, field := range fields {
|
||||
if field.profileKey == profileKey {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func assertFeatureConfigRoundTrips(t *testing.T, fields map[string]featureFieldBinding) {
|
||||
t.Helper()
|
||||
typeOfFeatures := reflect.TypeOf(config.FeaturesConfig{})
|
||||
for key, field := range fields {
|
||||
cfg := &config.Config{}
|
||||
features := reflect.ValueOf(&cfg.Features).Elem()
|
||||
ApplyStatesToConfig(cfg, []RuntimeFlagState{{Key: key, EffectiveValue: true}})
|
||||
if !features.Field(field.fieldIndex).Bool() {
|
||||
t.Fatalf("ApplyStatesToConfig(%q) did not enable target field %s", key, field.fieldName)
|
||||
}
|
||||
for i := 0; i < features.NumField(); i++ {
|
||||
if i != field.fieldIndex && features.Field(i).Bool() {
|
||||
t.Fatalf("ApplyStatesToConfig(%q) changed unrelated field %s", key, typeOfFeatures.Field(i).Name)
|
||||
}
|
||||
}
|
||||
if got := ValuesFromConfig(cfg)[key]; !got {
|
||||
t.Fatalf("ValuesFromConfig(%q) = false after enabling %s", key, field.fieldName)
|
||||
}
|
||||
ApplyStatesToConfig(cfg, []RuntimeFlagState{{Key: key, EffectiveValue: false}})
|
||||
if features.Field(field.fieldIndex).Bool() || ValuesFromConfig(cfg)[key] {
|
||||
t.Fatalf("ApplyStatesToConfig(%q) did not disable target field %s", key, field.fieldName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user