The user wants a cross-environment configuration promotion pipeline with specific features: freeze windows, approvals, and rollback.
1. Understand the Goal:
* Context: Managing configuration (Feature Flags, Environment Variables, Secrets, etc.) across multiple environments (e.g., Dev -> QA -> Staging -> Prod).
* Core Mechanism: Promotion (moving config changes from one env to the next).
* Key Constraints/Features:
* Freeze Windows: Times when changes aren't allowed (e.g., Black Friday, weekends).
* Approvals: Human gatekeeping before promotion.
* Rollback: Ability to revert to a previous state if things go wrong.
2. Determine the Implementation Strategy:
* Since no specific tool is requested (like LaunchDarkly, AWS AppConfig, or a custom Go script), I should design a conceptual architecture and then provide a concrete implementation example.
* Choice of Technology: A "pipeline" usually implies CI/CD (GitOps) or a specialized Feature Flag management tool.
* GitOps approach (using Git + CI/CD like GitHub Actions or GitLab CI) is the most robust, version-controlled, and "infrastructure-as-code" friendly way to demonstrate this. It allows for code-based approvals and history.
* Alternative: A custom service with a database. This is good for demonstrating the logic of freeze windows and state management.
code
*Decision:* I will implement a **Python-based orchestration engine** class that simulates this pipeline. This allows me to demonstrate the *logic* clearly without getting bogged down in specific CI/CD YAML syntax, though I will explain how to map this to CI/CD.
3. Component Design (The Python Class):
code
* **ConfigStore:** Simulates the storage of config snapshots.
* **Environments:** DEV, STAGING, PROD.
* **Freeze Window Logic:** A check `is_frozen(env)` based on date/time.
* **Approval Logic:** A state machine. `PENDING` -> `APPROVED`/`REJECTED`.
* **Promotion Logic:** Copying a snapshot ID from Source to Destination, checking freeze and approvals first.
* **Rollback Logic:** Reverting to a previous snapshot ID.
4. Drafting the Code Structure:
code
* *Class `ConfigPromoter`:*
* `__init__`: Setup environments, history.
* `create_snapshot(config)`: Create a versioned artifact.
* `promote(source, target, snapshot_id)`:
* Check Freeze.
* Request Approval.
* Apply.
* `approve(promotion_id)`: The gatekeeper action.
* `rollback(env, steps_back)`: The safety net.
5. Refining the Logic (Self-Correction during drafting):
* Issue: Promotion isn't instant if it requires approval.
* Fix:promote should create a "Promotion Request". A separate method execute_if_approved or the approve method itself triggers the actual application. Let's make it event-driven for realism.
* Simplified Model for Code: To make the code runnable and understandable in a single script:
1. Define a Pipeline class.
2. Implement is_frozen() checking against a list of blackout dates.
3. Implement request_promotion().
4. Implement approve_and_apply().
5. Implement rollback().
6. Flesh out details:
code
* **Freeze Windows:** Use `datetime` ranges.
* **Approvals:** In a real system, this is a PR review or a UI button click. In code, a simple boolean or list of approvers.
* **Rollback:** Needs a history stack per environment.
7. Structuring the Output:
* Conceptual Overview: Explain the architecture (GitOps vs. Config Service).
* Implementation (Python): A robust, object-oriented implementation of the logic.
* Integration Guide: How to map this logic to GitHub Actions or Jenkins.
8. Writing the Code (Mental Draft & Refinement):
* Mock Database: Use a dictionary to store config history.
* Freeze Logic: Check datetime.now().
* Promotion:env_state[prod] = env_state[staging].
* Rollback:env_state[prod] = history[prod][-2].
(Self-Correction during code writing): Make sure to handle the "In-Progress" state. If a promotion is requested but not approved, the config shouldn't change yet.
10. Output Generation: (Proceeding to generate the response based on the above structure). I will provide a Python implementation that simulates the engine behind such a pipeline, as this is the most transportable way to understand the logic.
(Self-Correction on Real-world Context): I should mention that tools like LaunchDarkly or Split.io exist, but the user asked to "Implement" one, implying building the logic or structure.
Let's build the Python implementation.
Enums: Environment (DEV, STAGE, PROD), Status (PENDING, APPLIED, REJECTED).
Refining the Rollback:
Rollback needs to be careful. Rolling back PROD should probably be automated or require less friction than a forward promotion, or maybe require high-level approval. For this example, I'll stick to a simple history-based revert.
Final Polish: Add comments and a usage example script at the bottom to demonstrate the flow.
This implementation uses a Python-based state machine to model the logic of a promotion pipeline. This approach is agnostic to the underlying infrastructure (it could be wired into Jenkins, GitHub Actions, or a Flask API) and focuses on the core requirements: state management, time-based constraints, and history tracking for rollbacks.
State Backend: Tracks which version is active in which environment (e.g., Redis, SQL, or file system).
Pipeline Engine: Enforces the rules defined below.
Implementation
python
Key Features Explained
1. Immutable Snapshots
The commit_config method creates a ConfigSnapshot with a SHA-256 hash ID. This ensures that the configuration being promoted is exactly the same as the one approved. You cannot modify the config in place; you must promote a new ID.
2. Freeze Windows
The _check_freeze method contains the logic to block promotions.
Implementation: In the code above, it checks if the current time matches a defined window (e.g., weekends or holidays).
Gate: It runs twice: once when the request is created (request_promotion) and once right before application (approve_and_apply). This prevents approving a change during safe hours that then waits in a queue and applies during a freeze window.
3. Approvals
The request_promotion method creates a PromotionRequest object. The system forces a separation of concerns:
Request: Developer/Bot creates the intent.
Apply: A human (or automated check) must call approve_and_apply.
Note: In a real enterprise setup, approve_and_apply would verify the actor has permissions (e.g., checking RBAC against the specific environment).
4. Rollback
The history dictionary acts as a stack.
Implementation: Every time a new config is applied, the previous config ID is pushed to the history stack for that environment.
Mechanism:rollback simply pops the last ID off the stack and sets it as the current active state. This is instant and requires no re-approval of the old config (by design).
Integration Strategy (Real World)
To move this from a script to a production system:
Storage: Replace the self.snapshots dictionary with a database (Postgres/MongoDB) or an Object Store (S3) for the config files.
State Locking: Use Redis or etcd to store environment_states to handle concurrency.
API Wrapper: Wrap the ConfigPipeline class in a REST API (FastAPI/Flask) so your CI/CD pipeline can trigger it via webhooks.
UI: Build a simple frontend that reads the API to show the "Approve" button and "Freeze" status indicators.
import json
import hashlib
import datetime
from enum import Enum, auto
from typing import Dict, List, Optional
# ==========================================
# 1. Data Structures & Enums
# ==========================================
class Environment(Enum):
DEV = auto()
STAGING = auto()
PROD = auto()
class PromotionStatus(Enum):
PENDING_APPROVAL = "pending_approval"
APPROVED = "approved"
FROZEN = "frozen_denied"
APPLIED = "applied"
class ConfigSnapshot:
def __init__(self, config_data: dict):
self.data = config_data
# Create a deterministic hash (ID) for the config
data_str = json.dumps(config_data, sort_keys=True)
self.id = hashlib.sha256(data_str.encode()).hexdigest()[:10]
self.created_at = datetime.datetime.now()
class PromotionRequest:
def __init__(self, snapshot_id: str, target_env: Environment):
self.snapshot_id = snapshot_id
self.target_env = target_env
self.status = PromotionStatus.PENDING_APPROVAL
self.approved_by = None
# ==========================================
# 2. The Pipeline Manager
# ==========================================
class ConfigPipeline:
def __init__(self):
# In-memory stores for demonstration (replace with DB in prod)
self.snapshots: Dict[str, ConfigSnapshot] = {}
self.environment_states: Dict[Environment, str] = {env: None for env in Environment}
self.history: Dict[Environment, List[str]] = {env: [] for env in Environment}
# Configuration: Define Freeze Windows (e.g., Production Freeze)
# Format: List of (Start_Day, Start_Hour, End_Day, End_Hour)
self.freeze_windows = {
Environment.PROD: [
("Friday", 17, "Monday", 9) # Freeze from Fri 5pm to Mon 9am
]
}
def _check_freeze(self, env: Environment) -> bool:
"""Checks if current time falls within a freeze window."""
if env not in self.freeze_windows:
return False # No freezes defined for this env
now = datetime.datetime.now()
current_day = now.strftime("%A")
current_hour = now.hour
# Simple logic for demonstration; production code needs robust datetime math
for start_day, start_hr, end_day, end_hr in self.freeze_windows[env]:
if current_day == start_day and current_hour >= start_hr:
return True
# Add logic for multi-day spans here...
return False
def commit_config(self, config_data: dict) -> str:
"""Ingests new config and returns an ID."""
snapshot = ConfigSnapshot(config_data)
self.snapshots[snapshot.id] = snapshot
print(f"✅ Committed Config ID: {snapshot.id}")
return snapshot.id
def request_promotion(self, snapshot_id: str, target_env: Environment) -> PromotionRequest:
"""Initiates a promotion request."""
if snapshot_id not in self.snapshots:
raise ValueError("Snapshot ID not found")
# Check Freeze Window immediately
if self._check_freeze(target_env):
print(f"🚫 Promotion to {target_env.name} blocked: Freeze Window Active.")
req = PromotionRequest(snapshot_id, target_env)
req.status = PromotionStatus.FROZEN
return req
req = PromotionRequest(snapshot_id, target_env)
print(f"📝 Promotion requested for {snapshot_id} -> {target_env.name}. Status: PENDING_APPROVAL")
return req
def approve_and_apply(self, request: PromotionRequest, approver: str):
"""Simulates the approval gate and applies the config."""
if request.status == PromotionStatus.FROZEN:
print("❌ Cannot approve frozen request.")
return
if request.status == PromotionStatus.APPLIED:
print("⚠️ Already applied.")
return
# Double check freeze window at approval time
if self._check_freeze(request.target_env):
print("🚫 Approval denied: Freeze Window engaged during approval process.")
request.status = PromotionStatus.FROZEN
return
# --- APPLY CONFIG ---
request.status = PromotionStatus.APPROVED
request.approved_by = approver
env = request.target_env
snapshot_id = request.snapshot_id
# Update current state
old_id = self.environment_states[env]
self.environment_states[env] = snapshot_id
# Update history for rollback
if old_id:
self.history[env].append(old_id)
print(f"🚀 SUCCESS: {env.name} updated to {snapshot_id} (Approved by: {approver})")
def rollback(self, env: Environment):
"""Reverts the environment to the previous configuration."""
if not self.history[env]:
print(f"⛔ Rollback failed: No history available for {env.name}")
return
last_config_id = self.history[env].pop()
self.environment_states[env] = last_config_id
print(f"⏪ ROLLBACK: {env.name} reverted to {last_config_id}")
def get_current_config(self, env: Environment) -> Optional[dict]:
current_id = self.environment_states[env]
if current_id and current_id in self.snapshots:
return self.snapshots[current_id].data
return None
# ==========================================
# 3. Usage Example
# ==========================================
if __name__ == "__main__":
pipeline = ConfigPipeline()
# 1. Dev creates a feature config
new_feature_config = {
"feature_x_enabled": True,
"db_pool_size": 10,
"api_version": "v2"
}
config_id = pipeline.commit_config(new_feature_config)
# 2. Promote to Staging (Usually auto-approved in real life, but forcing approval here)
# Note: We manually mock the approval logic here
staging_req = pipeline.request_promotion(config_id, Environment.STAGING)
if staging_req.status != PromotionStatus.FROZEN:
pipeline.approve_and_apply(staging_req, "dev_lead@example.com")
# 3. Promote to Prod
print("\n--- Initiating Prod Promotion ---")
prod_req = pipeline.request_promotion(config_id, Environment.PROD)
# 4. Approve Prod
# (This will succeed or fail depending on the time you run this script vs the hardcoded freeze window)
if prod_req.status != PromotionStatus.FROZEN:
pipeline.approve_and_apply(prod_req, "cto@example.com")
# 5. Simulate a catastrophic failure and Rollback
print("\n--- Simulating Incident & Rollback ---")
print(f"Current Prod Config: {pipeline.get_current_config(Environment.PROD)}")
pipeline.rollback(Environment.PROD)
print(f"Current Prod Config After Rollback: {pipeline.get_current_config(Environment.PROD)}")