The user asks: "Engineer a runtime feature policy enforcer toggling capabilities, validation, and monitoring."
Interpretation: They want a system/design/implementation for a runtime feature policy enforcer that can toggle capabilities (i.e., features), validate something, and monitor. This is a fairly high-level request, not a specific programming task. They likely want a design explanation and maybe code example or architecture. The user says "Engineer a runtime feature policy enforcer toggling capabilities, validation, and monitoring." It sounds like a software engineering task: design and implement a feature flag system (also known as feature toggle) that enforces policies at runtime, with validation and monitoring.
We need to produce a response that includes a clear design, perhaps using a language (likely Python, JavaScript, or Go). We should provide an architecture, core components, and a sample implementation. The user didn't specify language; we can choose a common one like Python or TypeScript. Also, they mention "toggling capabilities, validation, and monitoring." So we need to support toggling features (on/off), validation of feature state (maybe ensuring compliance with rules), and monitoring (logging metrics, maybe Prometheus). Could also include integration with external config source (like database, file, environment). And the enforcer should be able to be used in application code to guard features.
Thus, we should design a FeaturePolicyEnforcer class that loads feature definitions from a source, caches them, evaluates conditions (like user attributes, environment, rollout percentage), and allows checking if a feature is enabled. Also, it should have validation to ensure policies are well-formed and monitor usage (like counting checks).
We'll include:
Feature definition schema: name, enabled (bool) or conditions (percentage rollout, user groups, etc.), maybe dependencies.
Policy source: could be a JSON file, database, or remote config; we will abstract it.
Enforcer core: load policies, cache with TTL, evaluate conditions.
Capabilities: toggling (enable/disable) at runtime via API or admin UI; maybe reloading policies.
Validation: validate policies on load (schema, constraints like mutual exclusivity, required fields).
Monitoring: record metrics for feature checks (counts of allowed/denied), maybe hooks for logging, integration with metrics system.
Example usage: in a web app, check if feature is enabled before executing.
We can write in Python with type hints, using a simple in-memory store, but design for extensibility.
Alternatively, we could write in Go or TypeScript. Python is good for readability. We'll include a simple main to demonstrate.
Also, we might consider using a library like "featureflags" but we'll implement from scratch.
We'll structure the answer:
Introduction: what is a runtime feature policy enforcer.
Monitoring: metrics collector; maybe integrate with Prometheus client.
Implementation details: code snippets.
Example usage.
Discussion of toggling capabilities (admin API to change policies), validation, monitoring.
Conclusion.
We'll write code in Python, using dataclasses, threading for reload, maybe a simple HTTP server for toggling. But to keep it concise, maybe we'll show a command-line toggling and monitoring.
We can also show a more advanced design with strategy pattern for condition evaluation.
We need to be mindful that the user said "Engineer a runtime feature policy enforcer toggling capabilities, validation, and monitoring." They might expect a design and code that can be run. So we'll provide a complete example: a Python module that defines Enforcer, loads from YAML, has a simple REST endpoint to toggle (using Flask) and metrics endpoint (Prometheus). That might be overkill, but we can do a minimal version.
But to fit within answer length, we need to balance. We can provide a modular design and then partial code.
Better to produce a fairly comprehensive solution with code, but concise enough. We'll produce a single Python script that demonstrates everything: defines classes, loads policies from a dictionary (simulating source), validates, monitors via printing, and provides a CLI to toggle.
Maybe we can do a more robust solution: a class FeatureEnforcer with methods: is_enabled(feature_name, context=None). It uses policy store, and we have a background thread to reload policies periodically. To toggle, we can expose a function to update policy store (e.g., via HTTP). For simplicity, we'll simulate by directly updating a global dict, and the enforcer reloads.
Also validation: check that policy names are unique, conditions are valid (e.g., rollout between 0-100), etc.
Monitoring: we'll count checks per feature and outcome, and maybe log.
We'll implement a basic condition system: a feature can have:
enabled: bool (if True always on, if False always off)
rollout: percentage (0-100) - random check based on user_id hash or just random if no user_id.
groups: list of allowed group names (if context includes group)
environment: list of allowed env vars (like "production").
We'll design Condition class: evaluate(context) returns True/False. Context is a dict with keys like "user_id", "groups", "environment".
FeaturePolicy will have name and condition (or enabled flag). We'll treat enabled as a condition that always returns its value.
We'll create PolicyProvider: loads policies from a source. For demo, from a JSON file path.
PolicyValidator: after loading, validates each policy: name non-empty, if condition type known, parameters valid.
Enforcer: uses provider to get policies, stores in a cache (dict). It has a method to reload. The is_enabled method looks up policy, if not found returns False (or maybe configurable default). Then evaluates condition with context.
We'll also track usage: stats dict: feature_name -> {"allowed": count, "denied": count}. We'll protect with lock for thread safety if needed.
We can also expose a metrics endpoint using Flask to show stats. But maybe too heavy. We can just print stats on demand.
Given the user didn't specify language, but we can choose Python as it's common.
Now, let's write a response with explanation and code.
We'll start with an overview, then the design, then code.
Make sure to address all three aspects: toggling capabilities, validation, monitoring.
Toggling capabilities: we need a way to change policies at runtime, e.g., by updating the source file and reloading, or via an admin API that updates the in-memory policies (and optionally persists to source). We'll show both: file-based with auto-reload, and a simple HTTP PUT to update a policy in memory. For brevity, we might implement a simple Flask app with endpoints: /reload, /policies (GET, PUT), /metrics. That's a full solution. But if we want minimal, we could just show that toggling can be done by editing the source file and sending SIGHUP or calling reload. However, the prompt says "Engineer a runtime feature policy enforcer toggling capabilities", so we need to demonstrate toggling at runtime, i.e., without restart. So we'll include an admin API.
Given that we are to provide a solution that can be run, we can write a script that runs a Flask server that hosts the enforcer. That's a substantial code but manageable.
provider.py: FileProvider (loads from JSON file), ReloadableProvider (watches file changes or periodic reload).
validator.py: PolicyValidator class.
enforcer.py: FeatureEnforcer class, uses provider, validator, and has metrics.
app.py: Flask app exposing:
GET /features: list policies
PUT /features/:name: update policy (enable/disable or change conditions)
GET /metrics: JSON with stats
POST /reload: force reload from source
GET /check?feature=...&context=... (optional, to test)
We'll also include a main block to run Flask.
But we need to be careful to not overcomplicate; maybe we can combine into a single file for simplicity. The user might want the code as answer. We'll provide a single Python file that defines the enforcer and runs a demo with toggling via console input and monitoring via prints. That might be simpler and avoid needing Flask.
Let's think: The user said "Engineer a runtime feature policy enforcer toggling capabilities, validation, and monitoring." They might want a design and code, but not necessarily a full web service. We can provide a class-based design and then a small interactive script that demonstrates toggling through function calls and monitoring via printed stats. That's sufficient.
Alternatively, we can provide both: core class and then optional Flask integration. Since they asked "Engineer", they might expect a robust design. But we can keep it compact.
Given the time, I'll produce a Python script that:
Defines a FeaturePolicy dataclass with fields: name, enabled (bool) and optionally a condition which is a dict describing rollout or groups, etc.
A PolicyStore that holds policies, loads from a JSON file, and can update policies in memory. It has a reload method.
A PolicyValidator that validates policies after load or update.
A FeatureEnforcer that uses the store, has is_enabled(name, context={}), and records metrics.
A simple monitoring: after each check, we can print stats or query.
A demo loop: starts with some policies, allows user to type commands: "check ", "list", "toggle on/off", "update rollout ", "stats", "reload", "quit".
The user can see the effect immediately.
That's a "runtime" toggling because we update the store in memory, and enforcer uses it directly, no restart. Validation ensures updates are valid. Monitoring shows counts.
We'll implement condition evaluation: For simplicity, condition can be:
always: based on enabled flag.
rollout: percentage, using a deterministic hash of user_id to ensure consistent for same user.
groups: list, check context["groups"] contains at least one.
environment: check context["env"] matches one.
We'll combine conditions with AND logic: all must be true. Or we could allow OR, but simple.
We'll structure: FeaturePolicy has a condition dict with keys like "type": "rollout", "percentage": 50, or "type": "groups", "allowed_groups": ["admin"], etc. If no condition, enabled flag determines.
But for toggling capabilities, toggling simply means changing the enabled flag or condition parameters. So the admin can update via our commands.
Let's design code:
Data classes:
python
from dataclasses import dataclass
from typing import Dict, Any, List, Optional
import json
import os
import hashlib
import time
from threading import RLock
@dataclass
class FeaturePolicy:
name: str
enabled: bool = True
condition: Optional[Dict[str, Any]] = None # e.g., {"type": "rollout", "percentage": 50}
Condition evaluation:
python
def evaluate_condition(condition: Dict[str, Any], context: Dict[str, Any]) -> bool:
if condition is None:
return True
ctype = condition.get("type")
if ctype == "rollout":
percentage = condition["percentage"]
user_id = context.get("user_id")
if user_id is None:
# If no user_id, use random or fail? We'll treat as false.
return False
# Hash user_id to a number 0-99
hash_val = int(hashlib.sha256(str(user_id).encode()).hexdigest(), 16)
bucket = hash_val % 100
return bucket < percentage
elif ctype == "groups":
allowed = condition.get("allowed_groups", [])
user_groups = context.get("groups", [])
return any(g in allowed for g in user_groups)
elif ctype == "environment":
allowed_envs = condition.get("allowed_environments", [])
current_env = context.get("environment")
return current_env in allowed_envs
elif ctype == "custom":
# allow a lambda? not safe. skip.
return False
else:
return False
PolicyValidator:
python
class PolicyValidator:
def validate(self, policy: FeaturePolicy):
if not policy.name:
raise ValueError("Policy name cannot be empty")
if policy.condition:
ctype = policy.condition.get("type")
if ctype == "rollout":
pct = policy.condition.get("percentage")
if not isinstance(pct, (int, float)) or not (0 <= pct <= 100):
raise ValueError(f"Invalid rollout percentage: {pct}")
elif ctype == "groups":
groups = policy.condition.get("allowed_groups", [])
if not isinstance(groups, list):
raise ValueError("allowed_groups must be a list")
elif ctype == "environment":
envs = policy.condition.get("allowed_environments", [])
if not isinstance(envs, list):
raise ValueError("allowed_environments must be a list")
else:
raise ValueError(f"Unknown condition type: {ctype}")
PolicyStore:
python
class PolicyStore:
def __init__(self, policies: Optional[List[FeaturePolicy]] = None):
self._policies: Dict[str, FeaturePolicy] = {}
self._lock = RLock()
if policies:
self.update_policies(policies)
def update_policies(self, policies: List[FeaturePolicy]):
with self._lock:
new_dict = {}
for p in policies:
new_dict[p.name] = p
self._policies = new_dict
def get_policy(self, name: str) -> Optional[FeaturePolicy]:
with self._lock:
return self._policies.get(name)
def all_policies(self) -> List[FeaturePolicy]:
with self._lock:
return list(self._policies.values())
def update_policy(self, name: str, **kwargs) -> bool:
with self._lock:
if name not in self._policies:
return False
policy = self._policies[name]
for k, v in kwargs.items():
if hasattr(policy, k):
setattr(policy, k, v)
self._policies[name] = policy
return True
def reload_from_file(self, filepath: str):
with open(filepath, 'r') as f:
data = json.load(f)
policies = []
for item in data:
# item could be dict with name, enabled, condition
p = FeaturePolicy(**item)
policies.append(p)
self.update_policies(policies)
FeatureEnforcer:
python
class FeatureEnforcer:
def __init__(self, store: PolicyStore, validator: PolicyValidator):
self.store = store
self.validator = validator
self.metrics: Dict[str, Dict[str, int]] = {} # name -> {"allowed":0, "denied":0}
self.metrics_lock = RLock()
def is_enabled(self, feature_name: str, context: Optional[Dict[str, Any]] = None) -> bool:
policy = self.store.get_policy(feature_name)
if policy is None:
self._record_metric(feature_name, False)
return False
# First check enabled flag (if not enabled, deny even if condition passes)
if not policy.enabled:
self._record_metric(feature_name, False)
return False
# If condition exists, evaluate
if policy.condition:
try:
result = evaluate_condition(policy.condition, context or {})
except Exception as e:
# Log and deny
print(f"Error evaluating condition for {feature_name}: {e}")
result = False
else:
result = True
self._record_metric(feature_name, result)
return result
def _record_metric(self, feature: str, allowed: bool):
with self.metrics_lock:
metrics = self.metrics.setdefault(feature, {"allowed": 0, "denied": 0})
if allowed:
metrics["allowed"] += 1
else:
metrics["denied"] += 1
def get_metrics(self) -> Dict[str, Dict[str, int]]:
with self.metrics_lock:
return dict(self.metrics)
def validate_policy(self, policy: FeaturePolicy):
self.validator.validate(policy)
We also need a function to safely update policy in store and validate: store.update_policy then revalidate? Actually, validation should happen before update. So we'd have a method on enforcer to update policy: it validates, then store.update_policy.
But if we load from file, we need to validate all policies. In store.reload_from_file we could validate each before updating, but store doesn't know validator. So better let enforcer handle reload: enforcer.reload(filepath) that loads, validates, then updates store. So we can add:
python
def reload(self, filepath: str):
# Load and validate
with open(filepath) as f:
data = json.load(f)
policies = []
for item in data:
p = FeaturePolicy(**item)
self.validate_policy(p)
policies.append(p)
self.store.update_policies(policies)
Now toggling: we can have method to set enabled flag:
python
def toggle(self, feature: str, enabled: Optional[bool] = None):
# if enabled is None, flip current
policy = self.store.get_policy(feature)
if not policy:
raise KeyError(f"Feature {feature} not found")
current = policy.enabled
new_enabled = not current if enabled is None else enabled
policy.enabled = new_enabled
self.store.update_policy(feature, enabled=new_enabled)
But update_policy already modifies policy because we have reference; but after we modify we may need to update store dict? Actually store._policies holds reference, so modifying policy object is okay. But update_policy is avoidable; we can directly set policy.enabled because we have the reference. But then we need to verify after change? Not necessary.
Now monitoring: get_metrics returns stats.
We can create a demo: initial policies file "policies.json":
def main():
store = PolicyStore()
validator = PolicyValidator()
enforcer = FeatureEnforcer(store, validator)
# initial load
enforcer.reload("policies.json")
print("Loaded policies.")
# interactive loop
while True:
cmd = input("> ").strip()
if not cmd:
continue
parts = cmd.split()
if parts[0] == "quit":
break
elif parts[0] == "list":
for p in enforcer.store.all_policies():
print(f"{p.name}: enabled={p.enabled}, condition={p.condition}")
elif parts[0] == "stats":
metrics = enforcer.get_metrics()
for feature, m in metrics.items():
print(f"{feature}: allowed={m['allowed']}, denied={m['denied']}")
elif parts[0] == "check":
if len(parts) < 2:
print("Usage: check <feature> [context_json]")
continue
feature = parts[1]
context = {}
if len(parts) > 2:
context = json.loads(parts[2])
result = enforcer.is_enabled(feature, context)
print(f"Feature {feature} enabled: {result}")
elif parts[0] == "toggle":
if len(parts) < 2:
print("Usage: toggle <feature> [on|off]")
continue
feature = parts[1]
if len(parts) == 3:
enabled = parts[2].lower() == "on"
enforcer.toggle(feature, enabled)
else:
enforcer.toggle(feature)
print(f"Toggled {feature}")
elif parts[0] == "reload":
enforcer.reload("policies.json")
print("Reloaded policies from file.")
else:
print("Unknown command")
That would be a complete interactive demo.
We should also mention that the enforcer can be used as a library in production, with more robust source (like database), and monitoring integration with Prometheus or logging.
We'll also note that we included thread-safe locks for metrics and store operations, allowing the enforcer to be used in multi-threaded environments. In a web server, you'd call enforcer.is_enabled per request.
Now we need to produce a final answer: an explanation of the design and the code. We'll include the code as a single block for ease, with comments.
We'll start with "Solution Overview" and then "Code Implementation". Also include instructions on how to run the demo.
Make sure to cover validation: we validate policy schema on load and before updates. Monitoring: metrics collection.
Add a note about condition types extensibility: you can add more condition evaluators by registering.
Let's write the final answer accordingly.
We need to produce a professional response as a code expert.
We'll include proper imports, maybe use typing.
We'll also note that the demo uses a simple hash for rollout. In real use, you might want a consistent hash across multiple instances, maybe using a library.
We'll also note that the store reload is triggered manually; in production you could watch file changes or have API.
Now, the code:
We'll put everything in one file: feature_enforcer.py
Include:
imports
dataclasses
Condition evaluator function
PolicyValidator class
PolicyStore class
FeatureEnforcer class
main interactive loop
We'll also include a sample policies.json content in comments.
We'll add docstrings.
Let's craft the final answer.
Also, we might want to consider that the condition dict may have "type": "rollout", "percentage": 50, and also maybe "seed"? Not needed.
We'll be careful: the evaluate_condition uses context. For rollout, we use user_id; if not present, we could fallback to random if no user_id? But better to require user_id for deterministic rollout. We'll require.
We'll also add a condition for "ip_range"? Not needed.
Now, we'll write the answer.
We'll structure:
Introduction: purpose of runtime feature policy enforcer.
Design Principles: separation of concerns, thread-safety, validation, extensibility.
Extensibility and Production Considerations: replacing JSON file with DB, adding metrics to Prometheus, adding more condition types, using dependency injection.
Conclusion.
We'll write in a clear, professional tone.
Now, produce final answer.
Solution Overview
A runtime feature policy enforcer (also known as a feature‑flag or toggle system) allows applications to enable or disable functionality on the fly, often based on user attributes, environment, or rollout percentages. This solution provides:
Toggling capabilities – Policies can be changed at runtime without restarting the application (via file reload or an admin API).
Validation – Every policy is checked against a schema and business rules before it is applied, preventing invalid configurations.
Monitoring – The enforcer records how many times each feature was checked and whether it was allowed or denied, exposing these metrics for observability.
The design is modular, thread‑safe, and extensible. It consists of four core components:
Component
Responsibility
PolicyStore
Holds the current policies in memory. Supports atomic updates and can reload from a JSON file (or any source).
PolicyValidator
Verifies that a policy definition is syntactically correct and semantically sane (e.g., rollout percentage 0‑100).
ConditionEvaluator
A set of functions that evaluate a policy’s condition against a runtime context (user, groups, environment, …).
FeatureEnforcer
Public API: is_enabled(feature, context) consults the store, runs validation on updates, evaluates the condition, and records metrics.
The enforcer can be used directly in code (e.g., in a web request handler) or wrapped by an admin HTTP service. The implementation below is a self‑contained Python module that demonstrates all concepts with an interactive CLI.
Code Implementation
python
How It Works
1. Loading & Validation
Policies are stored in a JSON file (e.g., policies.json). Each entry contains name, enabled, and an optional condition.
When the enforcer starts or when reload is called, PolicyStore.reload_from_file reads the file, constructs FeaturePolicy objects, and passes each through PolicyValidator.validate.
The validator checks:
name is non‑empty.
enabled is a boolean.
Condition structure (e.g., percentage is numeric 0‑100, allowed_groups is a list).
Invalid policies raise an exception and prevent the store from being updated, ensuring the system never runs with broken configuration.
If a condition exists, evaluates it using the provided context dict.
Records the outcome in internal metrics.
Returns True (allowed) or False (denied).
The condition evaluator is pluggable; you can add new types by extending evaluate_condition.
3. Toggling Capabilities
Manual toggle:enforcer.toggle("feature") flips the enabled flag in memory.
Condition update:enforcer.update_condition("feature", new_condition) replaces the condition after validation.
Both operations take effect immediately – no restart required.
If you need persistence across restarts, the admin API should also write the changes back to the JSON file or a database. The demo stores changes only in memory, but the design makes persistence trivial.
4. Monitoring
Every call to is_enabled increments a counter (allowed or denied) for that feature.
enforcer.get_metrics() returns a snapshot of these counters.
In production you would push these to Prometheus, StatsD, or a logging system. The thread‑safe implementation ensures accuracy under concurrency.
5. Concurrency & Thread‑Safety
PolicyStore uses a re‑entrant lock (RLock) for all mutations and reads, making it safe for multi‑threaded environments (e.g., a web server handling many requests).
The metrics dictionary is also protected by its own lock.
Usage Example (Interactive Demo)
Start the demo:
bash
python3 feature_enforcer.py
The script creates a sample policies.json if missing and presents a command prompt.
Reload from file (if you edited policies.json in an external editor):
code
> reload
Quit:
code
> quit
All changes are reflected instantly because the enforcer operates on the in‑memory store.
Extending for Production
Feature
How to extend
Persistent source
Replace PolicyStore.reload_from_file with a database loader (SQL, Redis, etc.) and add save_policy for admin updates.
HTTP admin API
Wrap FeatureEnforcer in a Flask/FastAPI service exposing endpoints (GET /policies, PUT /policies/{name}, POST /reload, GET /metrics).
More condition types
Add a new elif ctype == "your_type" block in evaluate_condition and update the validator to check required fields.
Metrics system
Integrate with prometheus_client – create Counter objects and increment them instead of the internal dict.
Caching
Add an LRU cache around is_enabled for read‑heavy workloads (be careful with context sensitivity).
Audit logging
Log every toggle or condition update with user identity and timestamp.
The clean separation (PolicyStore/Validator/Enforcer) makes such enhancements straightforward.
Conclusion
This runtime feature policy enforcer satisfies the three core requirements:
Toggling – Policies can be changed live via admin commands or an API.
Validation – All policies are checked before they become active, guaranteeing correctness.
Monitoring – Built‑in metrics track how each feature is used, enabling data‑driven decisions.
The provided implementation is ready to run as a demo and can serve as a foundation for a production‑grade feature flag system.
#!/usr/bin/env python3
"""
Feature Policy Enforcer – runtime toggling, validation, and monitoring.
Author: OpenAI ChatGPT
Date: 2025‑04‑13
Core modules:
- PolicyStore: in‑memory store for FeaturePolicy objects.
- PolicyValidator: validates schema and business rules.
- FeatureEnforcer: public API, metrics collection, reload support.
- ConditionEvaluator: supports rollout, groups, environment.
Run the script for an interactive demo:
$ python3 feature_enforcer.py
"""
import json
import os
import sys
import hashlib
from dataclasses import dataclass, field
from typing import Dict, Any, List, Optional, Callable
from threading import RLock
from datetime import datetime
# ======================
# Data Model
# ======================
@dataclass
class FeaturePolicy:
"""Immutable representation of a feature policy."""
name: str
enabled: bool = True
# condition is a dict; known keys depend on 'type'.
condition: Optional[Dict[str, Any]] = None
# ======================
# Condition Evaluation
# ======================
def evaluate_condition(condition: Dict[str, Any], context: Dict[str, Any]) -> bool:
"""
Evaluate a condition against a context.
Supported condition types:
- rollout: {"type": "rollout", "percentage": 50}
Uses a deterministic hash of user_id to assign a bucket 0‑99.
Fails (deny) if user_id is missing.
- groups: {"type": "groups", "allowed_groups": ["admin"]}
Allows if any of the user's groups are in the allowed list.
- environment: {"type": "environment", "allowed_environments": ["production"]}
Allows if the current environment matches.
Returns True if condition holds, False otherwise.
"""
if condition is None:
return True
ctype = condition.get("type")
if ctype == "rollout":
percentage = condition.get("percentage")
if not isinstance(percentage, (int, float)) or not (0 <= percentage <= 100):
raise ValueError("Rollout percentage must be between 0 and 100")
user_id = context.get("user_id")
if user_id is None:
# Without a user identifier we cannot determine bucket -> deny
return False
# Deterministic bucket: hash -> 0‑99
h = hashlib.sha256(str(user_id).encode()).hexdigest()
bucket = int(h, 16) % 100
return bucket < percentage
elif ctype == "groups":
allowed = condition.get("allowed_groups", [])
if not isinstance(allowed, list):
raise ValueError("allowed_groups must be a list")
user_groups = context.get("groups", [])
return any(g in allowed for g in user_groups)
elif ctype == "environment":
allowed_envs = condition.get("allowed_environments", [])
if not isinstance(allowed_envs, list):
raise ValueError("allowed_environments must be a list")
current_env = context.get("environment")
return current_env in allowed_envs
else:
raise ValueError(f"Unsupported condition type: {ctype}")
# ======================
# Validation
# ======================
class PolicyValidator:
"""Validates a FeaturePolicy instance."""
def validate(self, policy: FeaturePolicy):
if not policy.name or not isinstance(policy.name, str):
raise ValueError("Policy name must be a non‑empty string")
if not isinstance(policy.enabled, bool):
raise ValueError("Policy enabled must be a boolean")
if policy.condition:
# Validate structure based on type
ctype = policy.condition.get("type")
if not ctype:
raise ValueError("Condition must have a 'type' key")
if ctype == "rollout":
pct = policy.condition.get("percentage")
if not isinstance(pct, (int, float)):
raise ValueError("Rollout percentage must be numeric")
if not (0 <= pct <= 100):
raise ValueError("Rollout percentage must be 0‑100")
elif ctype == "groups":
groups = policy.condition.get("allowed_groups")
if groups is not None and not isinstance(groups, list):
raise ValueError("allowed_groups must be a list or omitted")
elif ctype == "environment":
envs = policy.condition.get("allowed_environments")
if envs is not None and not isinstance(envs, list):
raise ValueError("allowed_environments must be a list or omitted")
else:
raise ValueError(f"Unknown condition type: {ctype}")
# ======================
# Policy Store
# ======================
class PolicyStore:
"""
Thread‑safe in‑memory store for FeaturePolicy objects.
Provides atomic updates and read‑only access.
"""
def __init__(self, policies: Optional[List[FeaturePolicy]] = None):
self._policies: Dict[str, FeaturePolicy] = {}
self._lock = RLock()
if policies:
self.update_policies(policies)
def update_policies(self, policies: List[FeaturePolicy]):
"""Replace the entire set of policies."""
with self._lock:
new_map = {}
for p in policies:
if p.name in new_map:
raise ValueError(f"Duplicate policy name: {p.name}")
new_map[p.name] = p
self._policies = new_map
def get_policy(self, name: str) -> Optional[FeaturePolicy]:
with self._lock:
return self._policies.get(name)
def all_policies(self) -> List[FeaturePolicy]:
with self._lock:
return list(self._policies.values())
def update_policy(self, name: str, **kwargs) -> bool:
"""Update mutable fields of a policy in place."""
with self._lock:
policy = self._policies.get(name)
if policy is None:
return False
# Only allow updating 'enabled' and 'condition' (which are mutable in our dataclass)
for key, value in kwargs.items():
if hasattr(policy, key):
setattr(policy, key, value)
else:
# Ignore unknowns or raise? We'll ignore for flexibility.
pass
return True
def reload_from_file(self, filepath: str, validator: PolicyValidator):
"""Load policies from a JSON file and replace the store after validation."""
if not os.path.exists(filepath):
raise FileNotFoundError(f"Policy file not found: {filepath}")
with open(filepath, "r") as f:
raw = json.load(f) # Expect list of dicts
policies = []
for raw_policy in raw:
p = FeaturePolicy(**raw_policy)
validator.validate(p)
policies.append(p)
self.update_policies(policies)
# ======================
# Feature Enforcer
# ======================
class FeatureEnforcer:
"""
Main façade. Use `is_enabled(feature, context)` to evaluate a feature flag.
Metrics are automatically collected.
"""
def __init__(self, store: PolicyStore, validator: PolicyValidator):
self.store = store
self.validator = validator
self._metrics: Dict[str, Dict[str, int]] = {} # feature -> {"allowed": N, "denied": M}
self._metrics_lock = RLock()
def is_enabled(self, feature_name: str, context: Optional[Dict[str, Any]] = None) -> bool:
"""Check if a feature is enabled for the given context."""
policy = self.store.get_policy(feature_name)
if policy is None:
self._record_metric(feature_name, allowed=False)
return False
# If the policy is globally disabled, short‑circuit
if not policy.enabled:
self._record_metric(feature_name, allowed=False)
return False
# Evaluate condition if present
if policy.condition:
try:
allowed = evaluate_condition(policy.condition, context or {})
except Exception as e:
# Log the error (in real code use logger) and treat as denied
print(f"[ERROR] Condition eval failed for {feature_name}: {e}")
allowed = False
else:
allowed = True
self._record_metric(feature_name, allowed)
return allowed
def _record_metric(self, feature: str, allowed: bool):
with self._metrics_lock:
if feature not in self._metrics:
self._metrics[feature] = {"allowed": 0, "denied": 0}
if allowed:
self._metrics[feature]["allowed"] += 1
else:
self._metrics[feature]["denied"] += 1
def get_metrics(self) -> Dict[str, Dict[str, int]]:
with self._metrics_lock:
return {k: v.copy() for k, v in self._metrics.items()}
# ---- Admin operations -------------------------------------------------
def toggle(self, feature: str, enabled: Optional[bool] = None):
"""
Flip or set the enabled flag of a policy.
Raises KeyError if feature does not exist.
"""
policy = self.store.get_policy(feature)
if policy is None:
raise KeyError(f"Feature '{feature}' not found")
new_enabled = not policy.enabled if enabled is None else bool(enabled)
# Directly mutate the policy object (store holds reference)
policy.enabled = new_enabled
# If using a persistent source you would also persist the change here.
print(f"Feature '{feature}' enabled set to {new_enabled}")
def update_condition(self, feature: str, condition: Dict[str, Any]):
"""
Replace the condition of a feature. The condition is validated before applying.
"""
policy = self.store.get_policy(feature)
if policy is None:
raise KeyError(f"Feature '{feature}' not found")
# Validate the new condition together with the policy's enabled flag.
# We create a temporary policy object for validation.
temp = FeaturePolicy(name=feature, enabled=policy.enabled, condition=condition)
self.validator.validate(temp)
policy.condition = condition
print(f"Condition for '{feature}' updated to {condition}")
def reload_policies(self, filepath: str):
"""Reload and replace all policies from the given JSON file."""
self.store.reload_from_file(filepath, self.validator)
print(f"Reloaded policies from {filepath}")
# ======================
# Demo / CLI
# ======================
def print_banner():
print("\n" + "=" * 60)
print(" Feature Policy Enforcer – Interactive Demo")
print("=" * 60)
print("Commands:")
print(" list – Show all policies")
print(" stats – Show usage metrics")
print(" check <feature> [context_json]")
print(" Evaluate a feature")
print(" toggle <feature> [on|off]")
print(" Enable/disable a feature (flip if no arg)")
print(" update <feature> <condition_json>")
print(" Set a new condition (e.g. rollout)")
print(" reload – Reload policies from policies.json")
print(" quit – Exit")
print("=" * 60 + "\n")
def interactive_demo():
# Path to policies file (must exist)
policies_file = "policies.json"
if not os.path.exists(policies_file):
print(f"Creating example '{policies_file}'...")
example = [
{"name": "new_ui", "enabled": False},
{"name": "beta_feature", "enabled": True,
"condition": {"type": "rollout", "percentage": 10}},
{"name": "admin_only", "enabled": True,
"condition": {"type": "groups", "allowed_groups": ["admin"]}},
{"name": "dark_mode", "enabled": True,
"condition": {"type": "environment", "allowed_environments": ["production", "staging"]}}
]
with open(policies_file, "w") as f:
json.dump(example, f, indent=2)
store = PolicyStore()
validator = PolicyValidator()
enforcer = FeatureEnforcer(store, validator)
# Initial load
enforcer.reload_policies(policies_file)
print_banner()
while True:
try:
cmd_line = input("> ").strip()
if not cmd_line:
continue
parts = cmd_line.split(maxsplit=2) # split into at most 3 parts
cmd = parts[0].lower()
if cmd == "quit":
print("Goodbye!")
break
elif cmd == "list":
print("\nCurrent policies:")
for p in enforcer.store.all_policies():
print(f" - {p.name}: enabled={p.enabled}, condition={p.condition}")
print()
elif cmd == "stats":
metrics = enforcer.get_metrics()
if not metrics:
print("\nNo checks recorded yet.\n")
else:
print("\nMetrics:")
for feature, m in metrics.items():
total = m["allowed"] + m["denied"]
print(f" {feature}: allowed={m['allowed']}, denied={m['denied']}, total={total}")
print()
elif cmd == "check":
if len(parts) < 2:
print("Usage: check <feature> [context_json]")
continue
feature = parts[1]
context = {}
if len(parts) > 2:
try:
context = json.loads(parts[2])
except json.JSONDecodeError as e:
print(f"Invalid JSON context: {e}")
continue
result = enforcer.is_enabled(feature, context)
print(f"Feature '{feature}' is {'ENABLED' if result else 'DISABLED'} for context {context}\n")
elif cmd == "toggle":
if len(parts) < 2:
print("Usage: toggle <feature> [on|off]")
continue
feature = parts[1]
if len(parts) == 3:
arg = parts[2].lower()
if arg == "on":
enforcer.toggle(feature, enabled=True)
elif arg == "off":
enforcer.toggle(feature, enabled=False)
else:
print("Second argument must be 'on' or 'off'")
continue
else:
enforcer.toggle(feature) # flip
elif cmd == "update":
if len(parts) < 3:
print("Usage: update <feature> <condition_json>")
continue
feature = parts[1]
try:
condition = json.loads(parts[2])
except json.JSONDecodeError as e:
print(f"Invalid JSON condition: {e}")
continue
try:
enforcer.update_condition(feature, condition)
except Exception as e:
print(f"Failed to update condition: {e}")
elif cmd == "reload":
try:
enforcer.reload_policies(policies_file)
except Exception as e:
print(f"Reload failed: {e}")
else:
print("Unknown command. Type 'help' for list of commands.")
except KeyboardInterrupt:
print("\nInterrupted. Type 'quit' to exit.")
except Exception as e:
print(f"Unexpected error: {e}")
if __name__ == "__main__":
interactive_demo()