Spaces:
Paused

yaz / src /core /feature_flags /flags.py
anaselamr's picture
v8.4.4: Auth & Security Hardening — Sprint 43 P2
091ca1d
Raw History Blame Contribute Delete
14.5 kB
"""
Feature Flags Core Implementation
Redis-backed with in-memory cache for performance
Performance: <5ms flag checks (cached), <50ms (Redis)
Patterns: Percentage rollout, tenant-specific, user-specific, time-based
"""
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from enum import Enum
from typing import Optional, Dict, Any, List, Set
from uuid import UUID
import hashlib
import json
import structlog
from functools import lru_cache
logger = structlog.get_logger(__name__)
class RolloutStrategy(str, Enum):
"""Feature rollout strategies"""
ALL = "all" # Enabled for everyone
NONE = "none" # Disabled for everyone
PERCENTAGE = "percentage" # Percentage-based rollout
TENANT_LIST = "tenant_list" # Specific tenants only
USER_LIST = "user_list" # Specific users only
BETA = "beta" # Beta testers only
INTERNAL = "internal" # Internal users only
TIME_BASED = "time_based" # Enabled during specific times
@dataclass
class FeatureFlag:
"""
Feature flag definition
Clinical Context: Control feature exposure for safe rollouts
Performance: Cached evaluation <5ms
"""
name: str
description: str
enabled: bool = False
strategy: RolloutStrategy = RolloutStrategy.NONE
# Rollout configuration
percentage: int = 0 # For PERCENTAGE strategy (0-100)
tenant_ids: Set[str] = field(default_factory=set) # For TENANT_LIST
user_ids: Set[str] = field(default_factory=set) # For USER_LIST
# Time-based configuration
start_time: Optional[datetime] = None
end_time: Optional[datetime] = None
# Metadata
category: str = "general"
owner: str = ""
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
# Dependencies
depends_on: List[str] = field(default_factory=list)
def is_enabled_for(
self,
tenant_id: Optional[str] = None,
user_id: Optional[str] = None,
attributes: Optional[Dict[str, Any]] = None
) -> bool:
"""
Check if feature is enabled for given context
Performance: <1ms (in-memory evaluation)
"""
if not self.enabled:
return False
if self.strategy == RolloutStrategy.ALL:
return True
if self.strategy == RolloutStrategy.NONE:
return False
if self.strategy == RolloutStrategy.TENANT_LIST:
return tenant_id in self.tenant_ids if tenant_id else False
if self.strategy == RolloutStrategy.USER_LIST:
return user_id in self.user_ids if user_id else False
if self.strategy == RolloutStrategy.PERCENTAGE:
if not tenant_id and not user_id:
return False
# Consistent hashing for stable rollout
key = f"{self.name}:{tenant_id or ''}:{user_id or ''}"
hash_value = int(hashlib.md5(key.encode()).hexdigest(), 16)
return (hash_value % 100) < self.percentage
if self.strategy == RolloutStrategy.TIME_BASED:
now = datetime.now(timezone.utc)
if self.start_time and now < self.start_time:
return False
if self.end_time and now > self.end_time:
return False
return True
if self.strategy == RolloutStrategy.BETA:
attrs = attributes or {}
return attrs.get("is_beta_tester", False)
if self.strategy == RolloutStrategy.INTERNAL:
attrs = attributes or {}
return attrs.get("is_internal", False)
return False
class FeatureFlagService:
"""
Feature flag service with Redis backend and in-memory cache
Performance:
- Cache hit: <5ms
- Cache miss: <50ms (Redis lookup)
- Cache refresh: Every 60 seconds
"""
_instance: Optional["FeatureFlagService"] = None
_cache: Dict[str, FeatureFlag] = {}
_cache_ttl: int = 60 # seconds
_last_refresh: Optional[datetime] = None
# Default flags for YAZ Care Platform
DEFAULT_FLAGS: Dict[str, Dict[str, Any]] = {
# Surgio - Surgery Management
"surgio.ai_risk_prediction": {
"description": "AI-powered surgical risk prediction",
"enabled": True,
"strategy": RolloutStrategy.ALL,
"category": "surgio",
"owner": "clinical-team"
},
"surgio.who_checklist_v2": {
"description": "WHO Surgical Safety Checklist 2.0",
"enabled": True,
"strategy": RolloutStrategy.ALL,
"category": "surgio",
"owner": "clinical-team"
},
"surgio.real_time_updates": {
"description": "Real-time SSE updates for OR board",
"enabled": True,
"strategy": RolloutStrategy.ALL,
"category": "surgio",
"owner": "platform-team"
},
"surgio.predictive_scheduling": {
"description": "AI-powered case scheduling optimization",
"enabled": True,
"strategy": RolloutStrategy.PERCENTAGE,
"percentage": 100,
"category": "surgio",
"owner": "ai-team"
},
# Clinica - Clinical Data
"clinica.news2_calculator": {
"description": "NEWS2 early warning score calculator",
"enabled": True,
"strategy": RolloutStrategy.ALL,
"category": "clinica",
"owner": "clinical-team"
},
"clinica.sepsis_screening": {
"description": "qSOFA sepsis screening tool",
"enabled": True,
"strategy": RolloutStrategy.ALL,
"category": "clinica",
"owner": "clinical-team"
},
# Labo - Laboratory
"labo.westgard_qc": {
"description": "Westgard QC rules engine",
"enabled": True,
"strategy": RolloutStrategy.ALL,
"category": "labo",
"owner": "lab-team"
},
"labo.delta_checks": {
"description": "Automatic delta check alerts",
"enabled": True,
"strategy": RolloutStrategy.ALL,
"category": "labo",
"owner": "lab-team"
},
# Platform-wide features
"platform.graphql_api": {
"description": "GraphQL API endpoint",
"enabled": True,
"strategy": RolloutStrategy.ALL,
"category": "platform",
"owner": "platform-team"
},
"platform.websocket_collaboration": {
"description": "Real-time WebSocket collaboration",
"enabled": True,
"strategy": RolloutStrategy.ALL,
"category": "platform",
"owner": "platform-team"
},
"platform.offline_mode": {
"description": "PWA offline mode support",
"enabled": True,
"strategy": RolloutStrategy.ALL,
"category": "platform",
"owner": "platform-team"
},
"platform.push_notifications": {
"description": "Web push notifications (VAPID)",
"enabled": True,
"strategy": RolloutStrategy.ALL,
"category": "platform",
"owner": "platform-team"
},
# Experimental features (controlled rollout)
"experimental.ai_documentation": {
"description": "AI-assisted clinical documentation",
"enabled": False,
"strategy": RolloutStrategy.BETA,
"category": "experimental",
"owner": "ai-team"
},
"experimental.voice_commands": {
"description": "Voice command interface",
"enabled": False,
"strategy": RolloutStrategy.INTERNAL,
"category": "experimental",
"owner": "innovation-team"
},
}
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._initialize()
return cls._instance
def _initialize(self):
"""Initialize with default flags"""
for name, config in self.DEFAULT_FLAGS.items():
strategy = config.get("strategy", RolloutStrategy.NONE)
if isinstance(strategy, str):
strategy = RolloutStrategy(strategy)
self._cache[name] = FeatureFlag(
name=name,
description=config.get("description", ""),
enabled=config.get("enabled", False),
strategy=strategy,
percentage=config.get("percentage", 0),
tenant_ids=set(config.get("tenant_ids", [])),
user_ids=set(config.get("user_ids", [])),
category=config.get("category", "general"),
owner=config.get("owner", ""),
)
self._last_refresh = datetime.now(timezone.utc)
def _should_refresh(self) -> bool:
"""Check if cache should be refreshed"""
if self._last_refresh is None:
return True
return datetime.now(timezone.utc) - self._last_refresh > timedelta(seconds=self._cache_ttl)
async def refresh_from_redis(self, redis_client=None):
"""Refresh flags from Redis (optional integration)"""
if redis_client is None:
return
try:
flags_data = await redis_client.hgetall("feature_flags")
if flags_data:
for name, data in flags_data.items():
flag_dict = json.loads(data)
self._cache[name] = FeatureFlag(**flag_dict)
self._last_refresh = datetime.now(timezone.utc)
except Exception as e:
logger.warning("feature_flags_redis_refresh_failed", error=str(e))
def get_flag(self, name: str) -> Optional[FeatureFlag]:
"""Get feature flag by name"""
return self._cache.get(name)
def is_enabled(
self,
name: str,
tenant_id: Optional[str] = None,
user_id: Optional[str] = None,
attributes: Optional[Dict[str, Any]] = None,
default: bool = False
) -> bool:
"""
Check if feature is enabled
Performance: <5ms (cached)
"""
flag = self._cache.get(name)
if flag is None:
logger.debug("feature_flag_not_found", flag_name=name, default=default)
return default
# Check dependencies
for dep_name in flag.depends_on:
if not self.is_enabled(dep_name, tenant_id, user_id, attributes):
return False
return flag.is_enabled_for(tenant_id, user_id, attributes)
def get_enabled_features(
self,
tenant_id: Optional[str] = None,
user_id: Optional[str] = None,
attributes: Optional[Dict[str, Any]] = None,
category: Optional[str] = None
) -> List[str]:
"""Get list of enabled feature names"""
enabled = []
for name, flag in self._cache.items():
if category and flag.category != category:
continue
if flag.is_enabled_for(tenant_id, user_id, attributes):
enabled.append(name)
return enabled
def set_flag(self, name: str, flag: FeatureFlag):
"""Set feature flag (in-memory, call save_to_redis to persist)"""
self._cache[name] = flag
def enable_for_tenant(self, name: str, tenant_id: str):
"""Enable feature for specific tenant"""
flag = self._cache.get(name)
if flag:
flag.tenant_ids.add(tenant_id)
flag.enabled = True
if flag.strategy == RolloutStrategy.NONE:
flag.strategy = RolloutStrategy.TENANT_LIST
def disable_for_tenant(self, name: str, tenant_id: str):
"""Disable feature for specific tenant"""
flag = self._cache.get(name)
if flag:
flag.tenant_ids.discard(tenant_id)
def set_percentage(self, name: str, percentage: int):
"""Set rollout percentage (0-100)"""
flag = self._cache.get(name)
if flag:
flag.percentage = max(0, min(100, percentage))
flag.strategy = RolloutStrategy.PERCENTAGE
flag.enabled = percentage > 0
def get_all_flags(self) -> Dict[str, FeatureFlag]:
"""Get all flags (for admin UI)"""
return self._cache.copy()
def to_client_config(
self,
tenant_id: Optional[str] = None,
user_id: Optional[str] = None
) -> Dict[str, bool]:
"""
Generate client-side config (for frontend)
Returns dict of {flag_name: enabled} for the given context
"""
return {
name: flag.is_enabled_for(tenant_id, user_id)
for name, flag in self._cache.items()
}
# Singleton instance
_feature_flags: Optional[FeatureFlagService] = None
def get_feature_flags() -> FeatureFlagService:
"""Get feature flags service instance"""
global _feature_flags
if _feature_flags is None:
_feature_flags = FeatureFlagService()
return _feature_flags
def is_feature_enabled(
name: str,
tenant_id: Optional[str] = None,
user_id: Optional[str] = None,
attributes: Optional[Dict[str, Any]] = None,
default: bool = False
) -> bool:
"""
Quick check if feature is enabled
Usage:
if is_feature_enabled("surgio.ai_risk_prediction", tenant_id=str(ctx.tenant_id)):
# Use AI prediction
else:
# Use standard calculation
"""
return get_feature_flags().is_enabled(name, tenant_id, user_id, attributes, default)
def get_enabled_features(
tenant_id: Optional[str] = None,
user_id: Optional[str] = None,
category: Optional[str] = None
) -> List[str]:
"""Get all enabled features for context"""
return get_feature_flags().get_enabled_features(tenant_id, user_id, category=category)