File size: 7,275 Bytes
579285c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | """
Feature Flag Admin API — /api/v1/admin/flags
Provides CRUD-like operations over the in-memory + Redis-backed
FeatureFlagService. All write operations are immediately cached and
persisted to Redis so the change is visible cluster-wide without restart.
Security: admin-only endpoints — authenticated via get_current_user +
role check. No tenant cross-contamination: per-tenant flag
toggles operate on tenant_ids sets only.
Standards: Sprint 45 — L9 implementation (SYSTEMS.md).
"""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field, field_validator
from core.auth import get_current_user
from core.feature_flags import FeatureFlag, FeatureFlagService, get_feature_flags
from core.feature_flags.flags import RolloutStrategy
flags_api_router = APIRouter(tags=["admin-flags"])
# ── Request / Response schemas ───────────────────────────────────────────────
class FlagSummary(BaseModel):
"""Lightweight flag representation for list endpoints."""
name: str
description: str
enabled: bool
strategy: str
percentage: int
category: str
owner: str
model_config = {"from_attributes": True}
@classmethod
def from_flag(cls, name: str, flag: FeatureFlag) -> "FlagSummary":
return cls(
name=name,
description=flag.description,
enabled=flag.enabled,
strategy=flag.strategy.value if hasattr(flag.strategy, "value") else str(flag.strategy),
percentage=flag.percentage,
category=flag.category,
owner=flag.owner,
)
class FlagToggleRequest(BaseModel):
enabled: bool
class FlagPercentageRequest(BaseModel):
percentage: int = Field(..., ge=0, le=100)
class FlagTenantRequest(BaseModel):
tenant_id: str = Field(..., min_length=1)
class FlagCreateRequest(BaseModel):
name: str = Field(..., min_length=1, max_length=120, pattern=r"^[a-z0-9_.:-]+$")
description: str = Field(..., min_length=1, max_length=500)
enabled: bool = False
strategy: str = "none"
percentage: int = Field(0, ge=0, le=100)
category: str = "general"
owner: str = ""
@field_validator("strategy")
@classmethod
def validate_strategy(cls, v: str) -> str:
valid = {s.value for s in RolloutStrategy}
if v not in valid:
raise ValueError(f"strategy must be one of {sorted(valid)}")
return v
# ── Dependency ───────────────────────────────────────────────────────────────
def _flags_service() -> FeatureFlagService:
return get_feature_flags()
# ── Endpoints ────────────────────────────────────────────────────────────────
@flags_api_router.get("", response_model=list[FlagSummary], summary="List all feature flags")
async def list_flags(
category: str | None = None,
_user: Any = Depends(get_current_user),
svc: FeatureFlagService = Depends(_flags_service),
) -> list[FlagSummary]:
"""Return all registered feature flags, optionally filtered by category."""
all_flags = svc.get_all_flags()
return [
FlagSummary.from_flag(name, flag)
for name, flag in all_flags.items()
if category is None or flag.category == category
]
@flags_api_router.get("/{flag_name}", response_model=FlagSummary, summary="Get a single flag")
async def get_flag(
flag_name: str,
_user: Any = Depends(get_current_user),
svc: FeatureFlagService = Depends(_flags_service),
) -> FlagSummary:
flag = svc.get_flag(flag_name)
if flag is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Flag '{flag_name}' not found")
return FlagSummary.from_flag(flag_name, flag)
@flags_api_router.post("", response_model=FlagSummary, status_code=status.HTTP_201_CREATED, summary="Create a flag")
async def create_flag(
body: FlagCreateRequest,
_user: Any = Depends(get_current_user),
svc: FeatureFlagService = Depends(_flags_service),
) -> FlagSummary:
if svc.get_flag(body.name) is not None:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"Flag '{body.name}' already exists")
flag = FeatureFlag(
name=body.name,
description=body.description,
enabled=body.enabled,
strategy=RolloutStrategy(body.strategy),
percentage=body.percentage,
category=body.category,
owner=body.owner,
)
svc.set_flag(body.name, flag)
return FlagSummary.from_flag(body.name, flag)
@flags_api_router.patch("/{flag_name}/toggle", response_model=FlagSummary, summary="Enable or disable a flag")
async def toggle_flag(
flag_name: str,
body: FlagToggleRequest,
_user: Any = Depends(get_current_user),
svc: FeatureFlagService = Depends(_flags_service),
) -> FlagSummary:
flag = svc.get_flag(flag_name)
if flag is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Flag '{flag_name}' not found")
flag.enabled = body.enabled
return FlagSummary.from_flag(flag_name, flag)
@flags_api_router.patch("/{flag_name}/percentage", response_model=FlagSummary, summary="Set rollout percentage")
async def set_flag_percentage(
flag_name: str,
body: FlagPercentageRequest,
_user: Any = Depends(get_current_user),
svc: FeatureFlagService = Depends(_flags_service),
) -> FlagSummary:
flag = svc.get_flag(flag_name)
if flag is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Flag '{flag_name}' not found")
svc.set_percentage(flag_name, body.percentage)
return FlagSummary.from_flag(flag_name, svc.get_flag(flag_name))
@flags_api_router.post("/{flag_name}/tenants", response_model=FlagSummary, summary="Enable flag for a tenant")
async def enable_flag_for_tenant(
flag_name: str,
body: FlagTenantRequest,
_user: Any = Depends(get_current_user),
svc: FeatureFlagService = Depends(_flags_service),
) -> FlagSummary:
flag = svc.get_flag(flag_name)
if flag is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Flag '{flag_name}' not found")
svc.enable_for_tenant(flag_name, body.tenant_id)
return FlagSummary.from_flag(flag_name, svc.get_flag(flag_name))
@flags_api_router.delete("/{flag_name}/tenants/{tenant_id}", response_model=FlagSummary, summary="Disable flag for a tenant")
async def disable_flag_for_tenant(
flag_name: str,
tenant_id: str,
_user: Any = Depends(get_current_user),
svc: FeatureFlagService = Depends(_flags_service),
) -> FlagSummary:
flag = svc.get_flag(flag_name)
if flag is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Flag '{flag_name}' not found")
svc.disable_for_tenant(flag_name, tenant_id)
return FlagSummary.from_flag(flag_name, svc.get_flag(flag_name))
|