simple-module-feature-flags 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ """FeatureFlags module."""
@@ -0,0 +1,31 @@
1
+ """Stable identifiers for the feature_flags module."""
2
+
3
+ PERM_FEATURE_FLAGS_VIEW = "feature_flags.view"
4
+ PERM_FEATURE_FLAGS_MANAGE = "feature_flags.manage"
5
+
6
+ # Prefix is load-bearing on SQLite, which has no per-module schemas.
7
+ TABLE_OVERRIDE = "feature_flags_override"
8
+ UQ_OVERRIDE_SCOPE_NAME = "uq_feature_flags_override_scope_scope_id_name"
9
+
10
+ SCOPE_SYSTEM = "system"
11
+ SCOPE_TENANT = "tenant"
12
+ ALL_SCOPES = (SCOPE_SYSTEM, SCOPE_TENANT)
13
+ # Empty string, not NULL: PG treats NULLs as distinct in unique indexes,
14
+ # which would let two "system" rows for the same flag coexist.
15
+ SYSTEM_SCOPE_ID = ""
16
+
17
+ SCOPE_MAX_LENGTH = 10
18
+ SCOPE_ID_MAX_LENGTH = 64
19
+
20
+ LOCALE_NAMESPACE = "feature_flags"
21
+
22
+ MENU_LABEL = "Feature Flags"
23
+ MENU_URL = "/feature_flags"
24
+ MENU_ICON = "flag"
25
+ MENU_ORDER = 45
26
+
27
+ PAGE_BROWSE = "FeatureFlags/Browse"
28
+
29
+ API_PREFIX = "/api/feature_flags"
30
+ VIEW_PREFIX = "/feature_flags"
31
+ QP_TENANT_ID = "tenant_id"
@@ -0,0 +1,13 @@
1
+ """feature_flags contracts — public interface for other modules."""
2
+
3
+ from feature_flags.contracts.schemas import (
4
+ FeatureFlagOverrideOut,
5
+ FeatureFlagView,
6
+ ToggleRequest,
7
+ )
8
+
9
+ __all__ = [
10
+ "FeatureFlagOverrideOut",
11
+ "FeatureFlagView",
12
+ "ToggleRequest",
13
+ ]
@@ -0,0 +1,47 @@
1
+ """SQLModel DTOs for the feature_flags module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+
7
+ from pydantic import ConfigDict
8
+ from sqlmodel import Field, SQLModel
9
+
10
+
11
+ class FeatureFlagOverrideOut(SQLModel):
12
+ """Stored override row as returned by the service/API."""
13
+
14
+ model_config = ConfigDict(from_attributes=True)
15
+
16
+ id: int
17
+ scope: str
18
+ scope_id: str
19
+ name: str
20
+ enabled: bool
21
+ created_at: datetime | None = None
22
+ updated_at: datetime | None = None
23
+
24
+
25
+ class FeatureFlagView(SQLModel):
26
+ """A flag as shown in the admin UI for a given scope.
27
+
28
+ ``enabled`` is the value an ``is_enabled(name, tenant_id=...)`` call
29
+ would return for this scope. ``overridden`` reports whether the row
30
+ that produced ``enabled`` lives at *this* scope (vs. inherited from
31
+ system or default). ``system_enabled`` exposes the underlying system
32
+ value when viewing a tenant scope, so the UI can show "inheriting:
33
+ on/off" next to the toggle.
34
+ """
35
+
36
+ name: str
37
+ description: str = ""
38
+ default_enabled: bool
39
+ enabled: bool
40
+ overridden: bool
41
+ system_enabled: bool | None = None
42
+
43
+
44
+ class ToggleRequest(SQLModel):
45
+ """Body for PUT /api/feature_flags/[tenant/{tenant_id}/]{name} — sets an override."""
46
+
47
+ enabled: bool = Field(...)
feature_flags/deps.py ADDED
@@ -0,0 +1,27 @@
1
+ """FastAPI dependencies for the feature_flags module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Annotated
6
+
7
+ from fastapi import Depends, Request
8
+ from simple_module_core.feature_flags import FeatureFlagRegistry
9
+ from simple_module_db.deps import get_db
10
+ from sqlalchemy.ext.asyncio import AsyncSession
11
+
12
+ from feature_flags.service import FeatureFlagService
13
+
14
+
15
+ async def get_feature_flag_service(
16
+ db: AsyncSession = Depends(get_db),
17
+ ) -> FeatureFlagService:
18
+ return FeatureFlagService(db)
19
+
20
+
21
+ def get_feature_flag_registry(request: Request) -> FeatureFlagRegistry:
22
+ """Return the process-wide FeatureFlagRegistry owned by the framework."""
23
+ return request.app.state.sm.feature_flags
24
+
25
+
26
+ FeatureFlagServiceDep = Annotated[FeatureFlagService, Depends(get_feature_flag_service)]
27
+ FeatureFlagRegistryDep = Annotated[FeatureFlagRegistry, Depends(get_feature_flag_registry)]
File without changes
@@ -0,0 +1,136 @@
1
+ """REST API endpoints for feature_flags management."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import APIRouter, Depends, HTTPException
6
+ from simple_module_core.feature_flags import FeatureFlagRegistry
7
+ from simple_module_hosting.permissions import RequiresPermission
8
+
9
+ from feature_flags.constants import (
10
+ PERM_FEATURE_FLAGS_MANAGE,
11
+ PERM_FEATURE_FLAGS_VIEW,
12
+ SCOPE_TENANT,
13
+ )
14
+ from feature_flags.contracts.schemas import FeatureFlagView, ToggleRequest
15
+ from feature_flags.deps import FeatureFlagRegistryDep, FeatureFlagServiceDep
16
+
17
+ router = APIRouter()
18
+
19
+
20
+ def _ensure_registered(name: str, registry: FeatureFlagRegistry) -> None:
21
+ # A typo here would silently persist a dead row that ``list_flags`` filters out.
22
+ if name not in {f.name for f in registry.all_flags}:
23
+ raise HTTPException(status_code=404, detail="Feature flag not registered")
24
+
25
+
26
+ @router.get(
27
+ "/",
28
+ response_model=list[FeatureFlagView],
29
+ dependencies=[Depends(RequiresPermission(PERM_FEATURE_FLAGS_VIEW))],
30
+ )
31
+ async def list_flags(
32
+ service: FeatureFlagServiceDep,
33
+ registry: FeatureFlagRegistryDep,
34
+ ) -> list[FeatureFlagView]:
35
+ return await service.list_flags(registry)
36
+
37
+
38
+ @router.get(
39
+ "/{name}",
40
+ response_model=FeatureFlagView,
41
+ dependencies=[Depends(RequiresPermission(PERM_FEATURE_FLAGS_VIEW))],
42
+ )
43
+ async def get_flag(
44
+ name: str,
45
+ service: FeatureFlagServiceDep,
46
+ registry: FeatureFlagRegistryDep,
47
+ ) -> FeatureFlagView:
48
+ view = service.build_view(registry, name)
49
+ if view is None:
50
+ raise HTTPException(status_code=404, detail="Feature flag not registered")
51
+ return view
52
+
53
+
54
+ @router.put(
55
+ "/{name}",
56
+ response_model=FeatureFlagView,
57
+ dependencies=[Depends(RequiresPermission(PERM_FEATURE_FLAGS_MANAGE))],
58
+ )
59
+ async def set_override(
60
+ name: str,
61
+ body: ToggleRequest,
62
+ service: FeatureFlagServiceDep,
63
+ registry: FeatureFlagRegistryDep,
64
+ ) -> FeatureFlagView:
65
+ _ensure_registered(name, registry)
66
+ await service.set_override(name, body.enabled, registry=registry)
67
+ view = service.build_view(registry, name)
68
+ assert view is not None # _ensure_registered already proved it exists
69
+ return view
70
+
71
+
72
+ @router.delete(
73
+ "/{name}",
74
+ status_code=204,
75
+ dependencies=[Depends(RequiresPermission(PERM_FEATURE_FLAGS_MANAGE))],
76
+ )
77
+ async def clear_override(
78
+ name: str,
79
+ service: FeatureFlagServiceDep,
80
+ registry: FeatureFlagRegistryDep,
81
+ ) -> None:
82
+ cleared = await service.clear_override(name, registry=registry)
83
+ if not cleared:
84
+ raise HTTPException(status_code=404, detail="No override set for this flag")
85
+
86
+
87
+ @router.get(
88
+ "/tenant/{tenant_id}",
89
+ response_model=list[FeatureFlagView],
90
+ dependencies=[Depends(RequiresPermission(PERM_FEATURE_FLAGS_VIEW))],
91
+ )
92
+ async def list_flags_for_tenant(
93
+ tenant_id: str,
94
+ service: FeatureFlagServiceDep,
95
+ registry: FeatureFlagRegistryDep,
96
+ ) -> list[FeatureFlagView]:
97
+ return await service.list_flags(registry, tenant_id=tenant_id)
98
+
99
+
100
+ @router.put(
101
+ "/tenant/{tenant_id}/{name}",
102
+ response_model=FeatureFlagView,
103
+ dependencies=[Depends(RequiresPermission(PERM_FEATURE_FLAGS_MANAGE))],
104
+ )
105
+ async def set_tenant_override(
106
+ tenant_id: str,
107
+ name: str,
108
+ body: ToggleRequest,
109
+ service: FeatureFlagServiceDep,
110
+ registry: FeatureFlagRegistryDep,
111
+ ) -> FeatureFlagView:
112
+ _ensure_registered(name, registry)
113
+ await service.set_override(
114
+ name, body.enabled, registry=registry, scope=SCOPE_TENANT, scope_id=tenant_id
115
+ )
116
+ view = service.build_view(registry, name, tenant_id=tenant_id)
117
+ assert view is not None # _ensure_registered already proved it exists
118
+ return view
119
+
120
+
121
+ @router.delete(
122
+ "/tenant/{tenant_id}/{name}",
123
+ status_code=204,
124
+ dependencies=[Depends(RequiresPermission(PERM_FEATURE_FLAGS_MANAGE))],
125
+ )
126
+ async def clear_tenant_override(
127
+ tenant_id: str,
128
+ name: str,
129
+ service: FeatureFlagServiceDep,
130
+ registry: FeatureFlagRegistryDep,
131
+ ) -> None:
132
+ cleared = await service.clear_override(
133
+ name, registry=registry, scope=SCOPE_TENANT, scope_id=tenant_id
134
+ )
135
+ if not cleared:
136
+ raise HTTPException(status_code=404, detail="No override set for this flag")
@@ -0,0 +1,98 @@
1
+ """Inertia view endpoints for feature_flags admin UI.
2
+
3
+ The browse page renders either system-scope or a tenant-scope view of the
4
+ flags. Tenant scope is selected via a ``tenant_id`` query string. The form
5
+ actions for toggling/clearing accept the same ``tenant_id`` query so the
6
+ frontend doesn't need separate routes per scope.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from fastapi import APIRouter, Depends, Request
12
+ from inertia import InertiaResponse
13
+ from simple_module_hosting.inertia_deps import InertiaDep
14
+ from simple_module_hosting.permissions import RequiresPermission
15
+ from starlette.responses import RedirectResponse
16
+
17
+ from feature_flags.constants import (
18
+ MENU_URL,
19
+ PAGE_BROWSE,
20
+ PERM_FEATURE_FLAGS_MANAGE,
21
+ PERM_FEATURE_FLAGS_VIEW,
22
+ QP_TENANT_ID,
23
+ SCOPE_SYSTEM,
24
+ SCOPE_TENANT,
25
+ SYSTEM_SCOPE_ID,
26
+ )
27
+ from feature_flags.deps import FeatureFlagRegistryDep, FeatureFlagServiceDep
28
+
29
+ router = APIRouter()
30
+
31
+
32
+ def _redirect_for_tenant(tenant_id: str | None) -> RedirectResponse:
33
+ target = MENU_URL if not tenant_id else f"{MENU_URL}?{QP_TENANT_ID}={tenant_id}"
34
+ return RedirectResponse(target, status_code=303)
35
+
36
+
37
+ def _scope_args(tenant_id: str | None) -> dict[str, str]:
38
+ if tenant_id:
39
+ return {"scope": SCOPE_TENANT, "scope_id": tenant_id}
40
+ return {"scope": SCOPE_SYSTEM, "scope_id": SYSTEM_SCOPE_ID}
41
+
42
+
43
+ @router.get(
44
+ "/",
45
+ response_model=None,
46
+ dependencies=[Depends(RequiresPermission(PERM_FEATURE_FLAGS_VIEW))],
47
+ )
48
+ async def browse(
49
+ inertia: InertiaDep,
50
+ service: FeatureFlagServiceDep,
51
+ registry: FeatureFlagRegistryDep,
52
+ tenant_id: str | None = None,
53
+ ) -> InertiaResponse:
54
+ flags = await service.list_flags(registry, tenant_id=tenant_id)
55
+ tenants = await service.list_tenants_with_overrides()
56
+ return await inertia.render(
57
+ PAGE_BROWSE,
58
+ {
59
+ "flags": [f.model_dump(mode="json") for f in flags],
60
+ "tenant_id": tenant_id,
61
+ "tenants": tenants,
62
+ },
63
+ )
64
+
65
+
66
+ @router.post(
67
+ "/{name}/toggle",
68
+ response_model=None,
69
+ dependencies=[Depends(RequiresPermission(PERM_FEATURE_FLAGS_MANAGE))],
70
+ )
71
+ async def toggle_action(
72
+ name: str,
73
+ request: Request,
74
+ service: FeatureFlagServiceDep,
75
+ registry: FeatureFlagRegistryDep,
76
+ tenant_id: str | None = None,
77
+ ) -> RedirectResponse:
78
+ if name not in {f.name for f in registry.all_flags}:
79
+ return _redirect_for_tenant(tenant_id)
80
+ body = await request.json()
81
+ enabled = bool(body.get("enabled", False))
82
+ await service.set_override(name, enabled, registry=registry, **_scope_args(tenant_id))
83
+ return _redirect_for_tenant(tenant_id)
84
+
85
+
86
+ @router.post(
87
+ "/{name}/clear",
88
+ response_model=None,
89
+ dependencies=[Depends(RequiresPermission(PERM_FEATURE_FLAGS_MANAGE))],
90
+ )
91
+ async def clear_action(
92
+ name: str,
93
+ service: FeatureFlagServiceDep,
94
+ registry: FeatureFlagRegistryDep,
95
+ tenant_id: str | None = None,
96
+ ) -> RedirectResponse:
97
+ await service.clear_override(name, registry=registry, **_scope_args(tenant_id))
98
+ return _redirect_for_tenant(tenant_id)
@@ -0,0 +1,40 @@
1
+ {
2
+ "browse": {
3
+ "title": "Feature Flags",
4
+ "description": "Toggle features exposed by installed modules. Overrides persist across restarts.",
5
+ "empty_title": "No feature flags registered",
6
+ "empty_description": "Modules declare flags via register_feature_flags(); install one to see it here.",
7
+ "count_one": "{count} flag",
8
+ "count_other": "{count} flags",
9
+ "viewing_system": "Viewing system-level flags. Switch scope to override per tenant.",
10
+ "viewing_tenant": "Viewing overrides for tenant \"{tenant_id}\". Tenant overrides beat the system value.",
11
+ "tenant_id_label": "Tenant ID",
12
+ "tenant_id_placeholder": "e.g. acme",
13
+ "scope_label": "Scope",
14
+ "scope_system": "System (all tenants)",
15
+ "scope_tenant": "Specific tenant",
16
+ "go": "View",
17
+ "back_to_system": "Back to system view",
18
+ "tenants_with_overrides": "Tenants with overrides"
19
+ },
20
+ "table": {
21
+ "name": "Flag",
22
+ "description": "Description",
23
+ "default": "Default",
24
+ "status": "Status",
25
+ "actions": "Actions",
26
+ "enabled": "Enabled",
27
+ "disabled": "Disabled",
28
+ "overridden": "Override active",
29
+ "following_default": "Following default",
30
+ "following_system": "Following system",
31
+ "system_value": "System: {value}",
32
+ "clear_override": "Clear override"
33
+ },
34
+ "toasts": {
35
+ "enabled": "\"{name}\" enabled",
36
+ "disabled": "\"{name}\" disabled",
37
+ "cleared": "Override cleared for \"{name}\"",
38
+ "toggle_failed": "Failed to update flag"
39
+ }
40
+ }
@@ -0,0 +1,42 @@
1
+ """SQLModel tables for the feature_flags module.
2
+
3
+ Stores persisted overrides for flags that modules declare via
4
+ ``register_feature_flags``. The definition of a flag (name, description,
5
+ default) lives in code; this table only records admin-applied overrides so
6
+ they survive across app restarts.
7
+
8
+ A row's ``scope`` selects whether the override applies globally
9
+ (``system``, ``scope_id=""``) or to a single tenant (``tenant``,
10
+ ``scope_id=<tenant_id>``). Resolution at runtime: tenant > system > default.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from simple_module_db.base import create_module_base
16
+ from simple_module_db.mixins import AuditMixin
17
+ from sqlalchemy import UniqueConstraint
18
+ from sqlmodel import Field
19
+
20
+ from feature_flags.constants import (
21
+ SCOPE_ID_MAX_LENGTH,
22
+ SCOPE_MAX_LENGTH,
23
+ SCOPE_SYSTEM,
24
+ SYSTEM_SCOPE_ID,
25
+ TABLE_OVERRIDE,
26
+ UQ_OVERRIDE_SCOPE_NAME,
27
+ )
28
+
29
+ Base = create_module_base("feature_flags")
30
+
31
+
32
+ class FeatureFlagOverride(Base, AuditMixin, table=True): # ty: ignore[unsupported-base]
33
+ """Persisted override for a single feature flag at a given scope."""
34
+
35
+ __tablename__ = TABLE_OVERRIDE
36
+ __table_args__ = (UniqueConstraint("scope", "scope_id", "name", name=UQ_OVERRIDE_SCOPE_NAME),)
37
+
38
+ id: int | None = Field(default=None, primary_key=True)
39
+ scope: str = Field(default=SCOPE_SYSTEM, max_length=SCOPE_MAX_LENGTH, index=True)
40
+ scope_id: str = Field(default=SYSTEM_SCOPE_ID, max_length=SCOPE_ID_MAX_LENGTH, index=True)
41
+ name: str = Field(max_length=200, index=True)
42
+ enabled: bool = Field(default=False)
@@ -0,0 +1,74 @@
1
+ """FeatureFlags module definition."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.resources
6
+ from pathlib import Path
7
+
8
+ from fastapi import APIRouter, FastAPI
9
+ from simple_module_core.menu import MenuItem, MenuRegistry, MenuSection
10
+ from simple_module_core.module import ModuleBase, ModuleMeta
11
+ from simple_module_core.permissions import PermissionRegistry
12
+
13
+ from feature_flags.constants import (
14
+ LOCALE_NAMESPACE,
15
+ MENU_ICON,
16
+ MENU_LABEL,
17
+ MENU_ORDER,
18
+ MENU_URL,
19
+ PERM_FEATURE_FLAGS_MANAGE,
20
+ PERM_FEATURE_FLAGS_VIEW,
21
+ )
22
+
23
+
24
+ class FeatureFlagsModule(ModuleBase):
25
+ meta = ModuleMeta(
26
+ name="FeatureFlags",
27
+ route_prefix="/api/feature_flags",
28
+ view_prefix="/feature_flags",
29
+ )
30
+
31
+ def register_routes(self, api_router: APIRouter, view_router: APIRouter) -> None:
32
+ from feature_flags.endpoints.api import router as api
33
+ from feature_flags.endpoints.views import router as views
34
+
35
+ api_router.include_router(api)
36
+ view_router.include_router(views)
37
+
38
+ def register_menu_items(self, registry: MenuRegistry) -> None:
39
+ registry.add(
40
+ MenuItem(
41
+ label=MENU_LABEL,
42
+ url=MENU_URL,
43
+ icon=MENU_ICON,
44
+ order=MENU_ORDER,
45
+ section=MenuSection.SIDEBAR,
46
+ )
47
+ )
48
+
49
+ def register_permissions(self, registry: PermissionRegistry) -> None:
50
+ registry.add_group(
51
+ "Feature Flags",
52
+ [
53
+ PERM_FEATURE_FLAGS_VIEW,
54
+ PERM_FEATURE_FLAGS_MANAGE,
55
+ ],
56
+ )
57
+
58
+ def locale_dirs(self) -> dict[str, Path]:
59
+ base = Path(str(importlib.resources.files(__package__) / "locales"))
60
+ return {LOCALE_NAMESPACE: base}
61
+
62
+ async def on_startup(self, app: FastAPI) -> None:
63
+ """Load every persisted override into the in-memory registry.
64
+
65
+ Called once, after DB init and before the app starts serving. From
66
+ here on ``registry.is_enabled`` reflects admin overrides even for
67
+ requests that don't hit this module's endpoints.
68
+ """
69
+ from feature_flags.service import FeatureFlagService
70
+
71
+ sm = app.state.sm
72
+ async with sm.db.session_factory() as session:
73
+ service = FeatureFlagService(session)
74
+ await service.hydrate_registry(sm.feature_flags)
@@ -0,0 +1,277 @@
1
+ import { router, usePage } from '@inertiajs/react';
2
+ import { keys, useT } from '@simple-module-py/i18n';
3
+ import { PageShell } from '@simple-module-py/ui/components/PageShell';
4
+ import { Badge } from '@simple-module-py/ui/components/ui/badge';
5
+ import { Button } from '@simple-module-py/ui/components/ui/button';
6
+ import { Card } from '@simple-module-py/ui/components/ui/card';
7
+ import {
8
+ Empty,
9
+ EmptyDescription,
10
+ EmptyMedia,
11
+ EmptyTitle,
12
+ } from '@simple-module-py/ui/components/ui/empty';
13
+ import { Input } from '@simple-module-py/ui/components/ui/input';
14
+ import { Switch } from '@simple-module-py/ui/components/ui/switch';
15
+ import {
16
+ Table,
17
+ TableBody,
18
+ TableCell,
19
+ TableHead,
20
+ TableHeader,
21
+ TableRow,
22
+ } from '@simple-module-py/ui/components/ui/table';
23
+ import { usePermissions } from '@simple-module-py/ui/hooks/use-permissions';
24
+ import { AuthenticatedLayout } from '@simple-module-py/ui/layouts/AuthenticatedLayout';
25
+ import { Flag, RotateCcw } from 'lucide-react';
26
+ import { useState } from 'react';
27
+ import { toast } from 'sonner';
28
+
29
+ interface FeatureFlag {
30
+ name: string;
31
+ description: string;
32
+ default_enabled: boolean;
33
+ enabled: boolean;
34
+ overridden: boolean;
35
+ system_enabled: boolean | null;
36
+ }
37
+
38
+ interface Props {
39
+ flags: FeatureFlag[];
40
+ tenant_id: string | null;
41
+ tenants: string[];
42
+ }
43
+
44
+ function buildPath(tenantId: string | null) {
45
+ return tenantId ? `/feature_flags?tenant_id=${encodeURIComponent(tenantId)}` : '/feature_flags';
46
+ }
47
+
48
+ function actionUrl(name: string, action: 'toggle' | 'clear', tenantId: string | null) {
49
+ const base = `/feature_flags/${name}/${action}`;
50
+ return tenantId ? `${base}?tenant_id=${encodeURIComponent(tenantId)}` : base;
51
+ }
52
+
53
+ function Browse() {
54
+ const { flags, tenant_id, tenants } = usePage<{ props: Props }>().props as unknown as Props;
55
+ const { t } = useT();
56
+ const { can } = usePermissions();
57
+ const canManage = can('feature_flags.manage');
58
+ const [tenantInput, setTenantInput] = useState(tenant_id ?? '');
59
+
60
+ function handleToggle(flag: FeatureFlag, next: boolean) {
61
+ router.post(
62
+ actionUrl(flag.name, 'toggle', tenant_id),
63
+ { enabled: next },
64
+ {
65
+ preserveScroll: true,
66
+ onSuccess: () =>
67
+ toast.success(
68
+ next
69
+ ? t(keys.feature_flags.toasts.enabled, { name: flag.name })
70
+ : t(keys.feature_flags.toasts.disabled, { name: flag.name }),
71
+ ),
72
+ onError: () => toast.error(t(keys.feature_flags.toasts.toggle_failed)),
73
+ },
74
+ );
75
+ }
76
+
77
+ function handleClear(flag: FeatureFlag) {
78
+ router.post(
79
+ actionUrl(flag.name, 'clear', tenant_id),
80
+ {},
81
+ {
82
+ preserveScroll: true,
83
+ onSuccess: () => toast.success(t(keys.feature_flags.toasts.cleared, { name: flag.name })),
84
+ onError: () => toast.error(t(keys.feature_flags.toasts.toggle_failed)),
85
+ },
86
+ );
87
+ }
88
+
89
+ function visitTenant(value: string) {
90
+ router.visit(buildPath(value.trim() || null));
91
+ }
92
+
93
+ return (
94
+ <PageShell
95
+ title={t(keys.feature_flags.browse.title)}
96
+ description={t(keys.feature_flags.browse.description)}
97
+ >
98
+ <Card className="mb-4 p-4">
99
+ <form
100
+ className="flex flex-wrap items-end gap-3"
101
+ onSubmit={(e) => {
102
+ e.preventDefault();
103
+ visitTenant(tenantInput);
104
+ }}
105
+ >
106
+ <div className="flex-1 min-w-[200px]">
107
+ <label className="block text-sm font-medium mb-1" htmlFor="tenant_id">
108
+ {t(keys.feature_flags.browse.tenant_id_label)}
109
+ </label>
110
+ <Input
111
+ id="tenant_id"
112
+ value={tenantInput}
113
+ onChange={(e) => setTenantInput(e.target.value)}
114
+ placeholder={t(keys.feature_flags.browse.tenant_id_placeholder)}
115
+ />
116
+ </div>
117
+ <Button type="submit" variant="default">
118
+ {t(keys.feature_flags.browse.go)}
119
+ </Button>
120
+ {tenant_id && (
121
+ <Button type="button" variant="ghost" onClick={() => visitTenant('')}>
122
+ {t(keys.feature_flags.browse.back_to_system)}
123
+ </Button>
124
+ )}
125
+ </form>
126
+ {tenants.length > 0 && (
127
+ <div className="mt-3 flex flex-wrap items-center gap-2 text-sm">
128
+ <span className="text-muted-foreground">
129
+ {t(keys.feature_flags.browse.tenants_with_overrides)}:
130
+ </span>
131
+ {tenants.map((tid) => (
132
+ <Button
133
+ key={tid}
134
+ type="button"
135
+ size="sm"
136
+ variant={tid === tenant_id ? 'default' : 'outline'}
137
+ onClick={() => visitTenant(tid)}
138
+ >
139
+ {tid}
140
+ </Button>
141
+ ))}
142
+ </div>
143
+ )}
144
+ <p className="mt-3 text-sm text-muted-foreground">
145
+ {tenant_id
146
+ ? t(keys.feature_flags.browse.viewing_tenant, { tenant_id })
147
+ : t(keys.feature_flags.browse.viewing_system)}
148
+ </p>
149
+ </Card>
150
+
151
+ <div className="mb-4 flex items-center justify-end">
152
+ {flags.length > 0 && (
153
+ <p className="text-sm text-muted-foreground">
154
+ {t(keys.feature_flags.browse.count, { count: flags.length })}
155
+ </p>
156
+ )}
157
+ </div>
158
+
159
+ <Card>
160
+ <Table>
161
+ <TableHeader>
162
+ <TableRow>
163
+ <TableHead className="sm:px-6">{t(keys.feature_flags.table.name)}</TableHead>
164
+ <TableHead className="hidden md:table-cell sm:px-6">
165
+ {t(keys.feature_flags.table.description)}
166
+ </TableHead>
167
+ <TableHead className="hidden sm:table-cell sm:px-6">
168
+ {t(keys.feature_flags.table.default)}
169
+ </TableHead>
170
+ <TableHead className="sm:px-6">{t(keys.feature_flags.table.status)}</TableHead>
171
+ {canManage && (
172
+ <TableHead className="text-right sm:px-6">
173
+ {t(keys.feature_flags.table.actions)}
174
+ </TableHead>
175
+ )}
176
+ </TableRow>
177
+ </TableHeader>
178
+ <TableBody>
179
+ {flags.map((flag) => (
180
+ <TableRow key={flag.name}>
181
+ <TableCell className="sm:px-6">
182
+ <div>
183
+ <span className="font-medium font-mono text-sm">{flag.name}</span>
184
+ {flag.overridden && (
185
+ <span className="ml-2 inline-block">
186
+ <Badge variant="secondary">{t(keys.feature_flags.table.overridden)}</Badge>
187
+ </span>
188
+ )}
189
+ </div>
190
+ </TableCell>
191
+ <TableCell className="hidden md:table-cell sm:px-6">
192
+ <span className="text-muted-foreground text-sm line-clamp-2">
193
+ {flag.description || '—'}
194
+ </span>
195
+ </TableCell>
196
+ <TableCell className="hidden sm:table-cell sm:px-6">
197
+ <span className="text-muted-foreground text-sm">
198
+ {flag.default_enabled
199
+ ? t(keys.feature_flags.table.enabled)
200
+ : t(keys.feature_flags.table.disabled)}
201
+ </span>
202
+ </TableCell>
203
+ <TableCell className="sm:px-6">
204
+ <div className="flex items-center gap-3">
205
+ <Switch
206
+ checked={flag.enabled}
207
+ onCheckedChange={(checked) => handleToggle(flag, checked === true)}
208
+ disabled={!canManage}
209
+ aria-label={flag.name}
210
+ />
211
+ <div className="flex flex-col">
212
+ <span className="text-sm text-muted-foreground">
213
+ {flag.enabled
214
+ ? t(keys.feature_flags.table.enabled)
215
+ : t(keys.feature_flags.table.disabled)}
216
+ </span>
217
+ {tenant_id && flag.system_enabled !== null && (
218
+ <span className="text-xs text-muted-foreground">
219
+ {t(keys.feature_flags.table.system_value, {
220
+ value: flag.system_enabled
221
+ ? t(keys.feature_flags.table.enabled)
222
+ : t(keys.feature_flags.table.disabled),
223
+ })}
224
+ </span>
225
+ )}
226
+ </div>
227
+ </div>
228
+ </TableCell>
229
+ {canManage && (
230
+ <TableCell className="text-right sm:px-6">
231
+ {flag.overridden ? (
232
+ <Button
233
+ variant="ghost"
234
+ size="sm"
235
+ onClick={() => handleClear(flag)}
236
+ title={t(keys.feature_flags.table.clear_override)}
237
+ >
238
+ <RotateCcw />
239
+ <span className="sr-only">
240
+ {t(keys.feature_flags.table.clear_override)}
241
+ </span>
242
+ </Button>
243
+ ) : (
244
+ <span className="text-xs text-muted-foreground">
245
+ {tenant_id
246
+ ? t(keys.feature_flags.table.following_system)
247
+ : t(keys.feature_flags.table.following_default)}
248
+ </span>
249
+ )}
250
+ </TableCell>
251
+ )}
252
+ </TableRow>
253
+ ))}
254
+ {flags.length === 0 && (
255
+ <TableRow>
256
+ <TableCell colSpan={5} className="h-40">
257
+ <Empty>
258
+ <EmptyMedia variant="icon">
259
+ <Flag className="size-5 text-primary-300" />
260
+ </EmptyMedia>
261
+ <EmptyTitle>{t(keys.feature_flags.browse.empty_title)}</EmptyTitle>
262
+ <EmptyDescription>
263
+ {t(keys.feature_flags.browse.empty_description)}
264
+ </EmptyDescription>
265
+ </Empty>
266
+ </TableCell>
267
+ </TableRow>
268
+ )}
269
+ </TableBody>
270
+ </Table>
271
+ </Card>
272
+ </PageShell>
273
+ );
274
+ }
275
+
276
+ Browse.layout = (page: React.ReactNode) => <AuthenticatedLayout>{page}</AuthenticatedLayout>;
277
+ export default Browse;
feature_flags/py.typed ADDED
File without changes
@@ -0,0 +1,189 @@
1
+ """FeatureFlagService — manages persisted overrides and syncs them to the registry.
2
+
3
+ Resolution semantics (tenant > system > default) live in
4
+ ``simple_module_core.feature_flags``; this layer only persists overrides and
5
+ mirrors mutations into the registry.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from simple_module_core.feature_flags import FeatureFlagDefinition, FeatureFlagRegistry
11
+ from sqlalchemy import select
12
+ from sqlalchemy.ext.asyncio import AsyncSession
13
+
14
+ from feature_flags.constants import SCOPE_SYSTEM, SCOPE_TENANT, SYSTEM_SCOPE_ID
15
+ from feature_flags.contracts.schemas import FeatureFlagOverrideOut, FeatureFlagView
16
+ from feature_flags.models import FeatureFlagOverride
17
+
18
+
19
+ def _registry_tenant_id(scope: str, scope_id: str) -> str | None:
20
+ """Translate a (scope, scope_id) pair into the registry's tenant_id arg."""
21
+ return scope_id if scope == SCOPE_TENANT else None
22
+
23
+
24
+ def _build_view(
25
+ flag: FeatureFlagDefinition,
26
+ *,
27
+ enabled: bool,
28
+ overridden: bool,
29
+ system_enabled: bool | None = None,
30
+ ) -> FeatureFlagView:
31
+ return FeatureFlagView(
32
+ name=flag.name,
33
+ description=flag.description,
34
+ default_enabled=flag.default_enabled,
35
+ enabled=enabled,
36
+ overridden=overridden,
37
+ system_enabled=system_enabled,
38
+ )
39
+
40
+
41
+ class FeatureFlagService:
42
+ """Read/write persisted overrides and keep the in-memory registry in sync.
43
+
44
+ The registry is the source of truth for *which* flags exist and their
45
+ defaults — those come from module code. This service owns the persisted
46
+ overrides at both system and tenant scope, mirroring every mutation back
47
+ into the registry so ``is_enabled`` returns the right value without an
48
+ extra DB hit per request.
49
+ """
50
+
51
+ def __init__(self, db: AsyncSession) -> None:
52
+ self.db = db
53
+
54
+ async def list_overrides(self) -> list[FeatureFlagOverrideOut]:
55
+ """Every persisted override across all scopes, ordered for stable display."""
56
+ result = await self.db.execute(
57
+ select(FeatureFlagOverride).order_by(
58
+ FeatureFlagOverride.scope,
59
+ FeatureFlagOverride.scope_id,
60
+ FeatureFlagOverride.name,
61
+ )
62
+ )
63
+ return [FeatureFlagOverrideOut.model_validate(row) for row in result.scalars()]
64
+
65
+ async def list_tenants_with_overrides(self) -> list[str]:
66
+ """Distinct tenant_ids that have at least one tenant-scope override."""
67
+ result = await self.db.execute(
68
+ select(FeatureFlagOverride.scope_id)
69
+ .where(FeatureFlagOverride.scope == SCOPE_TENANT)
70
+ .distinct()
71
+ .order_by(FeatureFlagOverride.scope_id)
72
+ )
73
+ return list(result.scalars())
74
+
75
+ async def list_flags(
76
+ self, registry: FeatureFlagRegistry, tenant_id: str | None = None
77
+ ) -> list[FeatureFlagView]:
78
+ """Join registered definitions with persisted overrides for admin display.
79
+
80
+ When ``tenant_id`` is None, the view is system-scoped: ``enabled``
81
+ reflects the system override (or default), and ``overridden`` is
82
+ true when a system row exists. When ``tenant_id`` is set, the view
83
+ is for that tenant: ``enabled`` is the resolved value the tenant
84
+ would see at runtime, ``overridden`` flags whether *this tenant*
85
+ has its own override, and ``system_enabled`` reports the value that
86
+ would apply if the tenant override were cleared.
87
+
88
+ Reads override state from the in-memory registry (kept in sync by
89
+ every mutation and rehydrated at startup) rather than re-querying
90
+ the DB, so admin page loads don't pay an O(rows) scan per request.
91
+ """
92
+ views: list[FeatureFlagView] = []
93
+ for flag in sorted(registry.all_flags, key=lambda f: f.name):
94
+ system_value = registry.system_override(flag.name)
95
+ system_enabled = system_value if system_value is not None else flag.default_enabled
96
+ if tenant_id is None:
97
+ views.append(
98
+ _build_view(flag, enabled=system_enabled, overridden=system_value is not None)
99
+ )
100
+ continue
101
+ tenant_value = registry.tenant_override(flag.name, tenant_id)
102
+ views.append(
103
+ _build_view(
104
+ flag,
105
+ enabled=tenant_value if tenant_value is not None else system_enabled,
106
+ overridden=tenant_value is not None,
107
+ system_enabled=system_enabled,
108
+ )
109
+ )
110
+ return views
111
+
112
+ def build_view(
113
+ self, registry: FeatureFlagRegistry, name: str, tenant_id: str | None = None
114
+ ) -> FeatureFlagView | None:
115
+ """Single-flag variant of ``list_flags`` for write-path responses."""
116
+ flag = next((f for f in registry.all_flags if f.name == name), None)
117
+ if flag is None:
118
+ return None
119
+ system_value = registry.system_override(name)
120
+ system_enabled = system_value if system_value is not None else flag.default_enabled
121
+ if tenant_id is None:
122
+ return _build_view(flag, enabled=system_enabled, overridden=system_value is not None)
123
+ tenant_value = registry.tenant_override(name, tenant_id)
124
+ return _build_view(
125
+ flag,
126
+ enabled=tenant_value if tenant_value is not None else system_enabled,
127
+ overridden=tenant_value is not None,
128
+ system_enabled=system_enabled,
129
+ )
130
+
131
+ async def _find(self, scope: str, scope_id: str, name: str) -> FeatureFlagOverride | None:
132
+ result = await self.db.execute(
133
+ select(FeatureFlagOverride).where(
134
+ FeatureFlagOverride.scope == scope,
135
+ FeatureFlagOverride.scope_id == scope_id,
136
+ FeatureFlagOverride.name == name,
137
+ )
138
+ )
139
+ return result.scalar_one_or_none()
140
+
141
+ async def set_override(
142
+ self,
143
+ name: str,
144
+ enabled: bool,
145
+ registry: FeatureFlagRegistry | None = None,
146
+ scope: str = SCOPE_SYSTEM,
147
+ scope_id: str = SYSTEM_SCOPE_ID,
148
+ ) -> FeatureFlagOverrideOut:
149
+ """Upsert an override at the given scope and mirror it to the registry."""
150
+ existing = await self._find(scope, scope_id, name)
151
+ if existing is None:
152
+ existing = FeatureFlagOverride(
153
+ scope=scope, scope_id=scope_id, name=name, enabled=enabled
154
+ )
155
+ self.db.add(existing)
156
+ await self.db.flush()
157
+ elif existing.enabled != enabled:
158
+ existing.enabled = enabled
159
+ await self.db.flush()
160
+ if registry is not None:
161
+ registry.set_override(name, enabled, tenant_id=_registry_tenant_id(scope, scope_id))
162
+ return FeatureFlagOverrideOut.model_validate(existing)
163
+
164
+ async def clear_override(
165
+ self,
166
+ name: str,
167
+ registry: FeatureFlagRegistry | None = None,
168
+ scope: str = SCOPE_SYSTEM,
169
+ scope_id: str = SYSTEM_SCOPE_ID,
170
+ ) -> bool:
171
+ """Delete the override at the given scope and revert the registry layer."""
172
+ existing = await self._find(scope, scope_id, name)
173
+ if existing is None:
174
+ return False
175
+ await self.db.delete(existing)
176
+ if registry is not None:
177
+ registry.clear_override(name, tenant_id=_registry_tenant_id(scope, scope_id))
178
+ return True
179
+
180
+ async def hydrate_registry(self, registry: FeatureFlagRegistry) -> int:
181
+ """Load every persisted override (system + tenant) into the registry at boot."""
182
+ overrides = await self.list_overrides()
183
+ for ovr in overrides:
184
+ registry.set_override(
185
+ ovr.name,
186
+ ovr.enabled,
187
+ tenant_id=_registry_tenant_id(ovr.scope, ovr.scope_id),
188
+ )
189
+ return len(overrides)
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: simple_module_feature_flags
3
+ Version: 0.0.1
4
+ Summary: Simple feature-flag module with per-tenant overrides and a consumer API for simple_module
5
+ Project-URL: Homepage, https://github.com/antosubash/simple_module_python
6
+ Project-URL: Repository, https://github.com/antosubash/simple_module_python
7
+ Project-URL: Issues, https://github.com/antosubash/simple_module_python/issues
8
+ Project-URL: Changelog, https://github.com/antosubash/simple_module_python/blob/main/CHANGELOG.md
9
+ Author-email: Anto Subash <antosubash@live.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: feature-flags,multi-tenant,simple-module,toggles
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Framework :: FastAPI
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Internet :: WWW/HTTP
21
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.12
24
+ Requires-Dist: simple-module-core==0.0.1
25
+ Requires-Dist: simple-module-db==0.0.1
26
+ Requires-Dist: simple-module-hosting==0.0.1
27
+ Description-Content-Type: text/markdown
28
+
29
+ # simple_module_feature_flags
30
+
31
+ Feature flags for [simple_module](https://github.com/antosubash/simple_module_python) apps. Global flags with per-tenant overrides, a tiny consumer API, and no external service to run.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install simple_module_feature_flags
37
+ ```
38
+
39
+ ## What it provides
40
+
41
+ - `Flag` and `TenantFlagOverride` SQLModel tables.
42
+ - `is_enabled("flag.name", tenant_id=...)` consumer API.
43
+ - Admin UI at `/feature-flags/admin` — toggle flags, add tenant overrides.
44
+ - Cache layer so checking a flag on every request is cheap.
45
+
46
+ ## Usage
47
+
48
+ Gate a route:
49
+
50
+ ```python
51
+ from feature_flags import is_enabled # type: ignore[import-not-found]
52
+ from fastapi import APIRouter, Depends, HTTPException
53
+
54
+ router = APIRouter()
55
+
56
+
57
+ @router.get("/new-feature")
58
+ async def new_feature(tenant_id: int = Depends(current_tenant_id)):
59
+ if not await is_enabled("orders.new_pricing_engine", tenant_id=tenant_id):
60
+ raise HTTPException(404)
61
+ return {"rolled_out": True}
62
+ ```
63
+
64
+ Seed a flag in a migration or admin UI:
65
+
66
+ ```python
67
+ # via migration
68
+ Flag(name="orders.new_pricing_engine", enabled=False)
69
+ ```
70
+
71
+ Tenant override:
72
+
73
+ ```python
74
+ TenantFlagOverride(tenant_id=7, flag_name="orders.new_pricing_engine", enabled=True)
75
+ ```
76
+
77
+ ## Depends on
78
+
79
+ - `simple_module_core`, `simple_module_db`, `simple_module_hosting`
80
+
81
+ ## License
82
+
83
+ MIT — see [LICENSE](https://github.com/antosubash/simple_module_python/blob/main/LICENSE).
@@ -0,0 +1,19 @@
1
+ feature_flags/__init__.py,sha256=2-MI5-QCdUtM0-c57j8-uCZ_lpFSecfzH84gorSLIqo,27
2
+ feature_flags/constants.py,sha256=eVmFf83nyi1yI3sXXDshkGkIkokPSbXo2eE65HW8rRQ,894
3
+ feature_flags/deps.py,sha256=rCHnBHwTFx_2PxH3bdhYqjlwTvnJegYmANiWkacblLo,887
4
+ feature_flags/models.py,sha256=aA4t8mvJAyFrm16w4sXYZRGH4HeOXchY-EucxS7nakE,1559
5
+ feature_flags/module.py,sha256=vX9pRx1KnVnJeYVi_i2kWavwoXYv2tIxCgaelxNPp2w,2350
6
+ feature_flags/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ feature_flags/service.py,sha256=BJsoId79_RnRr7LSc1k5Ms6bQXT7XH5nGW_DPSVynsE,7837
8
+ feature_flags/contracts/__init__.py,sha256=JkGBkOohqMEjeGdkN8ZZ_uzQ1qqOjyJFB9KL-Ukzz-c,276
9
+ feature_flags/contracts/schemas.py,sha256=fia1IW0IkI2yP48Yp9uMoDXnSriUGneYuVey_pcPgQ0,1297
10
+ feature_flags/endpoints/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ feature_flags/endpoints/api.py,sha256=lE0kG3UnQ7KvvTGZpK4LT4_9py1nWdUdxRIUUvzDAfU,4179
12
+ feature_flags/endpoints/views.py,sha256=sqdgd_OPYiGKdkI0e7SzwMw5tvQ5K-mWFo7OrMLwX_g,3065
13
+ feature_flags/locales/en.json,sha256=BKoMFbnHEH3Q0Y0t5kHOaXl6SoXvOiQpBUAexb8Qyhg,1487
14
+ feature_flags/pages/Browse.tsx,sha256=MPBePp2vl7t9ODU4GAuOojEbbBEdl8WEKZhb7ukqOZo,10346
15
+ simple_module_feature_flags-0.0.1.dist-info/METADATA,sha256=a3PWObqIC6xIEigCrX6EzA9UzxdKagI82PmiG3eFni0,2720
16
+ simple_module_feature_flags-0.0.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
17
+ simple_module_feature_flags-0.0.1.dist-info/entry_points.txt,sha256=-_bxddecOgjR9-dLOTGYrXwM-KKj2Bg82w36O6uQ9jg,72
18
+ simple_module_feature_flags-0.0.1.dist-info/licenses/LICENSE,sha256=Yn66lhLklsF5p7pa85_ksQrJ79Q-FgOaUAHevLBjer4,1068
19
+ simple_module_feature_flags-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [simple_module]
2
+ feature_flags = feature_flags.module:FeatureFlagsModule
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anto Subash
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.