import hashlib
import time
import json
import threading
from typing import Dict, Optional, Any, List
from dataclasses import dataclass, asdict
from enum import Enum
class RampMode(Enum):
"""Ramp modes for automated percentage increases."""
MANUAL = "manual"
LINEAR = "linear" # Steady increase over time
EXPONENTIAL = "exponential" # Accelerating increase
@dataclass
class RampSchedule:
"""Defines a ramp schedule with steps."""
mode: RampMode
target_percent: float
duration_hours: float # Total time to reach target
step_interval_seconds: int = 60 # How often to check/adjust
@dataclass
class ConfigState:
"""Serializable state of a config."""
name: str
percent: float = 0.0
frozen_until: float = 0.0
ramp_schedule: Optional[RampSchedule] = None
metadata: Dict[str, Any] = None
class DynamicConfig:
"""Manages a single dynamic config with percent-based rollout."""
def __init__(self, name: str, initial_percent: float = 0.0):
self.name = name
self._percent = initial_percent
self._frozen_until = 0.0
self._ramp_schedule: Optional[RampSchedule] = None
self._ramp_thread: Optional[threading.Thread] = None
self._stop_ramp = threading.Event()
self.metadata: Dict[str, Any] = {}
@property
def percent(self) -> float:
return self._percent
@property
def frozen_until(self) -> float:
return self._frozen_until
@property
def is_frozen(self) -> bool:
return time.time() < self._frozen_until
@property
def is_ramping(self) -> bool:
return self._ramp_thread is not None and self._ramp_thread.is_alive()
def set_percent(self, percent: float, force: bool = False) -> bool:
"""Set rollout percentage (0-100). Returns True if applied."""
if force or not self.is_frozen:
self._percent = max(0.0, min(100.0, percent))
return True
return False
def freeze(self, duration_hours: float) -> None:
"""Freeze changes until timestamp."""
self._frozen_until = time.time() + (duration_hours * 3600)
self._stop_ramp_active_ramp()
def unfreeze(self) -> None:
"""Immediately unfreeze."""
self._frozen_until = 0.0
def start_ramp(self, schedule: RampSchedule) -> None:
"""Start automated ramping in a background thread."""
if self.is_ramping:
self.stop_ramp()
self._ramp_schedule = schedule
self._stop_ramp.clear()
self._ramp_thread = threading.Thread(target=self._ramp_worker, daemon=True)
self._ramp_thread.start()
def stop_ramp(self) -> None:
"""Stop automated ramping."""
self._stop_ramp.set()
if self._ramp_thread:
self._ramp_thread.join(timeout=1.0)
self._ramp_schedule = None
def _stop_ramp_active_ramp(self) -> None:
"""Internal: Stop ramp if active."""
if self.is_ramping:
self.stop_ramp()
def _ramp_worker(self) -> None:
"""Background worker for ramping."""
if not self._ramp_schedule:
return
start_time = time.time()
duration = self._ramp_schedule.duration_hours * 3600
step_interval = self._ramp_schedule.step_interval_seconds
while not self._stop_ramp.wait(step_interval):
if time.time() - start_time >= duration:
break
elapsed = time.time() - start_time
progress = min(1.0, elapsed / duration)
if self._ramp_schedule.mode == RampMode.LINEAR:
new_percent = self._ramp_schedule.target_percent * progress
elif self._ramp_schedule.mode == RampMode.EXPONENTIAL:
new_percent = self._ramp_schedule.target_percent * (progress ** 2) # Quadratic for expo feel
else: # MANUAL
break
# Only adjust if not frozen
if not self.is_frozen:
self.set_percent(new_percent)
# Final set to target if not frozen
if not self.is_frozen:
self.set_percent(self._ramp_schedule.target_percent)
def is_active_for_user(self, user_id: str) -> bool:
"""Check if feature is active for user based on percent ramp."""
if self.percent <= 0:
return False
# Deterministic user bucketing (stable across runs)
user_hash = int(hashlib.md5(user_id.encode('utf-8')).hexdigest(), 16) % 100
return user_hash < self.percent
def to_dict(self) -> Dict[str, Any]:
"""Serialize state."""
return asdict(ConfigState(
name=self.name,
percent=self.percent,
frozen_until=self.frozen_until,
ramp_schedule=self._ramp_schedule,
metadata=self.metadata
))
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'DynamicConfig':
"""Deserialize state."""
state = ConfigState(**data)
cfg = cls(state.name, state.percent)
cfg._frozen_until = state.frozen_until
cfg.metadata = state.metadata or {}
if state.ramp_schedule:
cfg.start_ramp(state.ramp_schedule)
return cfg
class DynamicConfigSystem:
"""Full dynamic config system with persistence support."""
def __init__(self, storage_file: Optional[str] = None):
self.configs: Dict[str, DynamicConfig] = {}
self._storage_file = storage_file
self._load()
def get_config(self, name: str) -> DynamicConfig:
"""Get or create config."""
if name not in self.configs:
self.configs[name] = DynamicConfig(name)
return self.configs[name]
def remove_config(self, name: str) -> None:
"""Remove config."""
if name in self.configs:
self.configs[name].stop_ramp()
del self.configs[name]
self._save()
def is_active(self, name: str, user_id: str) -> bool:
"""Quick check: Is config active for user?"""
return self.get_config(name).is_active_for_user(user_id)
def set_percent(self, name: str, percent: float, force: bool = False) -> bool:
"""Set percent for config."""
success = self.get_config(name).set_percent(percent, force)
self._save()
return success
def freeze(self, name: str, duration_hours: float) -> None:
"""Freeze config."""
self.get_config(name).freeze(duration_hours)
self._save()
def unfreeze(self, name: str) -> None:
"""Unfreeze config."""
self.get_config(name).unfreeze()
self._save()
def start_ramp(self, name: str, schedule: RampSchedule) -> None:
"""Start ramp for config."""
self.get_config(name).start_ramp(schedule)
self._save()
def stop_ramp(self, name: str) -> None:
"""Stop ramp for config."""
self.get_config(name).stop_ramp()
self._save()
def _save(self) -> None:
"""Persist to JSON file."""
if not self._storage_file:
return
state = {name: cfg.to_dict() for name, cfg in self.configs.items()}
with open(self._storage_file, 'w') as f:
json.dump(state, f, indent=2, default=str)
def _load(self) -> None:
"""Load from JSON file."""
if not self._storage_file or not os.path.exists(self._storage_file):
return
try:
with open(self._storage_file, 'r') as f:
state = json.load(f)
self.configs = {
data['name']: DynamicConfig.from_dict(data)
for data in state.values()
}
except Exception:
pass # Ignore load errors
# Example usage
if __name__ == "__main__":
import os
# Init system with file persistence
system = DynamicConfigSystem(storage_file="configs.json")
# Create/use config
cfg = system.get_config("new_feature_flag")
# Manual ramp example
system.set_percent("new_feature_flag", 1.0) # 1% rollout
print(system.is_active("new_feature_flag", "user123")) # Maybe True/False based on hash
system.set_percent("new_feature_flag", 10.0)
# Freeze for 2 hours
system.freeze("new_feature_flag", 2.0)
print("Frozen:", cfg.is_frozen)
# Auto-ramp example: Linear to 50% over 1 hour
schedule = RampSchedule(
mode=RampMode.LINEAR,
target_percent=50.0,
duration_hours=1.0,
step_interval_seconds=30
)
system.start_ramp("new_feature_flag", schedule)
# Simulate time passing (in real use, let thread run)
time.sleep(5) # Let it ramp a bit
print("Current %:", cfg.percent)
system.stop_ramp("new_feature_flag")
# Test user rollout
users = ["alice", "bob", "charlie"]
for user in users:
print(f"{user} gets feature: {system.is_active('new_feature_flag', user)}")
# Persist on changes
Key Features
- Percent Ramps: Manual
set_percent() or automated via start_ramp() with linear or exponential schedules.
- Freezes:
freeze(duration_hours) locks changes (including ramps) until expiry. force=True bypasses.
- Dynamic: Runtime updates, background threading for ramps, user-specific rollout via stable MD5 hash (0-99 buckets).
- Persistence: JSON file storage (
configs.json) for state across restarts.
- Thread-Safe: Daemon threads for ramps, proper cleanup.
- Extensible: Metadata dict, easy serialization.
How Rollout Works: Users are hashed into 100 buckets. If percent=25, first 25 buckets get it. Deterministic & sticky.
Elementary! Deploy, tweak, and scale. Need tweaks (e.g., Redis backend)? Just ask. 🚀