package main
import (
"context"
"fmt"
"log"
"math/rand"
"sync"
"time"
)
// ==========================================
// 1. Domain Models & Audit
// ==========================================
// AuditEntry records a change to the system.
type AuditEntry struct {
Timestamp time.Time
User string // The admin who made the change
FlagName string
Action string // e.g., "CREATED", "KILLED", "UPDATED_RULES"
Details string
}
// TargetingRule defines logic for matching a user.
type TargetingRule struct {
Type string // "PERCENTAGE" or "ATTRIBUTE"
Key string // e.g., "Region" or "UserID"
Value string // e.g., "US-East"
Threshold int // Used for percentage (0-100)
}
// FeatureFlag holds the state.
type FeatureFlag struct {
Name string
Description string
Enabled bool // The "Kill Switch"
Rules []TargetingRule
Variants map[string]string // e.g., "control": "blue_button", "treatment": "red_button"
CreatedAt time.Time
ExpiresAt time.Time // For Cleanup Policy
}
// EvaluationContext represents the user requesting the feature.
type EvaluationContext struct {
UserID string
Attributes map[string]string
}
// ==========================================
// 2. Interfaces
// ==========================================
// ExperimentHook allows external systems to react to an evaluation.
type ExperimentHook interface {
OnEvaluate(flagName string, ctx EvaluationContext, result bool, variant string)
}
// AuditLogger persists audit trails.
type AuditLogger interface {
Log(entry AuditEntry)
}
// ==========================================
// 3. Core Service
// ==========================================
type FeatureFlagService struct {
mu sync.RWMutex
flags map[string]*FeatureFlag
auditLog AuditLogger
hooks []ExperimentHook
cleanupTick time.Duration
}
func NewFeatureFlagService(audit AuditLogger) *FeatureFlagService {
return &FeatureFlagService{
flags: make(map[string]*FeatureFlag),
auditLog: audit,
}
}
// CreateFlag initializes a new feature flag.
func (s *FeatureFlagService) CreateFlag(adminUser string, flag FeatureFlag) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, exists := s.flags[flag.Name]; exists {
return fmt.Errorf("flag %s already exists", flag.Name)
}
flag.CreatedAt = time.Now()
s.flags[flag.Name] = &flag
s.auditLog.Log(AuditEntry{
Timestamp: time.Now(),
User: adminUser,
FlagName: flag.Name,
Action: "CREATED",
Details: fmt.Sprintf("Description: %s", flag.Description),
})
return nil
}
// ToggleKillSwitch immediately enables or disables a flag globally.
func (s *FeatureFlagService) ToggleKillSwitch(adminUser, flagName string, enable bool) error {
s.mu.Lock()
defer s.mu.Unlock()
flag, exists := s.flags[flagName]
if !exists {
return fmt.Errorf("flag not found")
}
flag.Enabled = enable
action := "KILL_SWITCH_ACTIVATED"
if enable {
action = "KILL_SWITCH_DEACTIVATED"
}
s.auditLog.Log(AuditEntry{
Timestamp: time.Now(),
User: adminUser,
FlagName: flagName,
Action: action,
})
return nil
}
// IsEnabled evaluates the flag for a specific user context.
// Logic: Kill Switch -> Targeting Rules -> Default False
func (s *FeatureFlagService) IsEnabled(flagName string, ctx EvaluationContext) (bool, string) {
s.mu.RLock()
defer s.mu.RUnlock()
flag, exists := s.flags[flagName]
if !exists {
return false, "FLAG_NOT_FOUND"
}
// 1. KILL SWITCH CHECK
if !flag.Enabled {
s.triggerHooks(flagName, ctx, false, "disabled_kill_switch")
return false, "disabled_kill_switch"
}
// 2. TARGETING RULES
// We check specific attributes first, then fall back to percentage.
for _, rule := range flag.Rules {
switch rule.Type {
case "ATTRIBUTE":
if val, ok := ctx.Attributes[rule.Key]; ok && val == rule.Value {
s.triggerHooks(flagName, ctx, true, "matched_attribute")
return true, "matched_attribute"
}
case "PERCENTAGE":
// Deterministic hash for consistent user experience
hash := simpleHash(ctx.UserID + flagName)
if hash%100 < rule.Threshold {
s.triggerHooks(flagName, ctx, true, "rolled_out")
return true, "rolled_out"
}
}
}
// 3. DEFAULT
s.triggerHooks(flagName, ctx, false, "default_fallback")
return false, "default_fallback"
}
func (s *FeatureFlagService) AddHook(hook ExperimentHook) {
s.hooks = append(s.hooks, hook)
}
func (s *FeatureFlagService) triggerHooks(name string, ctx EvaluationContext, res bool, variant string) {
for _, h := range s.hooks {
// Fire and forget (in prod, use goroutines or worker pools)
go h.OnEvaluate(name, ctx, res, variant)
}
}
// ==========================================
// 4. Cleanup Policy
// ==========================================
// StartCleanupPolicy runs a background goroutine to remove expired flags.
func (s *FeatureFlagService) StartCleanupPolicy(ctx context.Context) {
ticker := time.NewTicker(10 * time.Second) // Check every 10 seconds for demo purposes
go func() {
for {
select {
case <-ctx.Done():
ticker.Stop()
return
case <-ticker.C:
s.cleanupExpiredFlags()
}
}
}()
}
func (s *FeatureFlagService) cleanupExpiredFlags() {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
for name, flag := range s.flags {
if !flag.ExpiresAt.IsZero() && now.After(flag.ExpiresAt) {
log.Printf("[CLEANUP] Removing expired flag: %s", name)
delete(s.flags, name)
s.auditLog.Log(AuditEntry{
Timestamp: time.Now(),
User: "SYSTEM",
FlagName: name,
Action: "AUTO_DELETED",
Details: "Expired by cleanup policy",
})
}
}
}
// Simple helper for deterministic hashing
func simpleHash(s string) int {
h := 0
for _, c := range s {
h += int(c)
}
return h % 100
}
// ==========================================
// 5. Main Demonstration
// ==========================================
// Mock implementation of AuditLogger
type ConsoleAuditLogger struct{}
func (l *ConsoleAuditLogger) Log(entry AuditEntry) {
fmt.Printf("[AUDIT] %s | User: %-8s | Flag: %-15s | Action: %s\n",
entry.Timestamp.Format("15:04:05"), entry.User, entry.FlagName, entry.Action)
}
// Mock implementation of ExperimentHook
type AnalyticsHook struct{}
func (h *AnalyticsHook) OnEvaluate(flag string, ctx EvaluationContext, result bool, variant string) {
// Send to Datadog/Mixpanel here
// fmt.Printf(" -> [HOOK] Sent impression to Analytics for user %s\n", ctx.UserID)
}
func main() {
// Setup
audit := &ConsoleAuditLogger{}
svc := NewFeatureFlagService(audit)
svc.AddHook(&AnalyticsHook{})
// Context for cleanup
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
svc.StartCleanupPolicy(ctx)
fmt.Println("--- 1. Creating Flags ---")
// Standard Flag
svc.CreateFlag("Admin_Alice", FeatureFlag{
Name: "new_checkout_ui",
Description: "Rollout of the V2 checkout",
Enabled: true,
Rules: []TargetingRule{
{Type: "ATTRIBUTE", Key: "BetaTester", Value: "true"},
{Type: "PERCENTAGE", Threshold: 50}, // 50% rollout
},
})
// Temporary Flag (To test cleanup)
expiration := time.Now().Add(15 * time.Second)
svc.CreateFlag("Admin_Bob", FeatureFlag{
Name: "black_friday_sale",
Enabled: true,
ExpiresAt: expiration,
Description: "Temporary campaign",
})
fmt.Println("\n--- 2. Evaluation (Targeting) ---")
user1 := EvaluationContext{UserID: "123", Attributes: map[string]string{"BetaTester": "true"}}
user2 := EvaluationContext{UserID: "999", Attributes: map[string]string{"Region": "US"}}
// User 1 matches Attribute rule
val, _ := svc.IsEnabled("new_checkout_ui", user1)
fmt.Printf("User %s sees feature: %v\n", user1.UserID, val)
// User 2 falls to percentage (and fails based on hash)
val, _ = svc.IsEnabled("new_checkout_ui", user2)
fmt.Printf("User %s sees feature: %v\n", user2.UserID, val)
fmt.Println("\n--- 3. Kill Switch Activation ---")
// Alice hits the kill switch because of a bug
svc.ToggleKillSwitch("Admin_Alice", "new_checkout_ui", false)
// Evaluate again
val, _ = svc.IsEnabled("new_checkout_ui", user1)
fmt.Printf("User %s sees feature after Kill Switch: %v\n", user1.UserID, val)
fmt.Println("\n--- 4. Cleanup Policy Demonstration ---")
fmt.Println("Waiting for 'black_friday_sale' to expire (waiting 16 seconds)...")
// Sleep to demonstrate background cleanup
time.Sleep(16 * time.Second)
// Try to access the expired flag
val, _ = svc.IsEnabled("black_friday_sale", user1)
fmt.Printf("Expired flag check result: %v\n", val)
}