|
| 1 | +import os |
| 2 | +from enum import IntFlag, auto |
| 3 | +from functools import reduce |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from pydantic import Field, ValidationInfo, field_validator |
| 7 | +from pydantic_settings import BaseSettings, SettingsConfigDict |
| 8 | + |
| 9 | + |
| 10 | +class Features(IntFlag): |
| 11 | + """A flag enum for setting specific application behaviors through feature |
| 12 | + flags. |
| 13 | + """ |
| 14 | + |
| 15 | + API_V1 = auto() |
| 16 | + API_V2 = auto() |
| 17 | + DAEMON_CAMPAIGNS = auto() |
| 18 | + DAEMON_NODES = auto() |
| 19 | + DAEMON_V1 = auto() |
| 20 | + DAEMON_V2 = auto() |
| 21 | + WEBAPP_V1 = auto() |
| 22 | + |
| 23 | + |
| 24 | +class EnabledFeatures(BaseSettings): |
| 25 | + """Pydantic Settings class for managing the enabled features of an |
| 26 | + application.""" |
| 27 | + |
| 28 | + model_config = SettingsConfigDict( |
| 29 | + env_prefix="FEATURE_", |
| 30 | + case_sensitive=False, |
| 31 | + extra="allow", |
| 32 | + ) |
| 33 | + |
| 34 | + enabled: Features = Field( |
| 35 | + description="A Flag Enum for enabled application features.", default=Features(0) |
| 36 | + ) |
| 37 | + |
| 38 | + @field_validator("enabled") |
| 39 | + @classmethod |
| 40 | + def determine_enabled_features(cls, data: Any, info: ValidationInfo) -> Any: |
| 41 | + """Check all environment variables according to the `env_prefix` of the |
| 42 | + model config and set/unset feature flags for the matching feature. |
| 43 | + """ |
| 44 | + if (env_prefix := cls.model_config.get("env_prefix")) is None: |
| 45 | + return data |
| 46 | + enabled = set() |
| 47 | + disabled = set() |
| 48 | + for feature_env_var in filter(lambda k: k.startswith(env_prefix), os.environ.keys()): |
| 49 | + try: |
| 50 | + if os.getenv(feature_env_var, "false").strip().lower() in ("1", "t", "true", "yes", "on"): |
| 51 | + enabled.add(Features[feature_env_var.replace(env_prefix, "")]) |
| 52 | + else: |
| 53 | + disabled.add(Features[feature_env_var.replace(env_prefix, "")]) |
| 54 | + except KeyError: |
| 55 | + # no matching feature |
| 56 | + pass |
| 57 | + |
| 58 | + data = reduce(lambda x, y: x | y, enabled, data) |
| 59 | + data = reduce(lambda x, y: x & ~y, disabled, data) |
| 60 | + return data |
0 commit comments