Ir para o conteúdo

tempest_fastapi_sdk.flags

Feature flags: o serviço, os backends (memória, env, Redis, composto) e a dependência do FastAPI.

« Tempo real e mensageria


FeatureFlags

FeatureFlags(backend: FeatureFlagBackend, *, default: bool = False)

Read and toggle boolean feature flags over a backend.

Wrap any :class:FeatureFlagBackend and branch on flags in services or gate routes with :func:tempest_fastapi_sdk.flags.make_flag_dependency::

flags = FeatureFlags(RedisFeatureFlagBackend(redis.client))
if await flags.is_enabled("new_checkout"):
    ...

Initialize the service.

Parameters:

Name Type Description Default
backend FeatureFlagBackend

The storage backend.

required
default bool

Value returned for a flag the backend has no entry for (get → None). Defaults to False so unknown flags are off.

False

is_enabled async

is_enabled(name: str, *, default: bool | None = None) -> bool

Return whether name is enabled.

Parameters:

Name Type Description Default
name str

The flag name.

required
default bool | None

Per-call override of the service default for an unset flag. None uses the service default.

None

Returns:

Name Type Description
bool bool

The flag value, or the resolved default when unset.

enable async

enable(name: str) -> None

Turn name on (delegates to the backend).

Parameters:

Name Type Description Default
name str

The flag name.

required

disable async

disable(name: str) -> None

Turn name off (delegates to the backend).

Parameters:

Name Type Description Default
name str

The flag name.

required

set async

set(name: str, enabled: bool) -> None

Set name to enabled (delegates to the backend).

Parameters:

Name Type Description Default
name str

The flag name.

required
enabled bool

The value to persist.

required

all async

all() -> dict[str, bool]

Return every known flag as a {name: enabled} mapping.

Returns:

Type Description
dict[str, bool]

dict[str, bool]: Every known flag as {name: enabled}.

FeatureFlagBackend

Bases: Protocol

Storage backend for boolean feature flags.

get async

get(name: str) -> bool | None

Return the flag value, or None when it is unset.

Parameters:

Name Type Description Default
name str

The flag name.

required

Returns:

Type Description
bool | None

bool | None: The flag value, or None when it is unset.

set async

set(name: str, enabled: bool) -> None

Persist enabled for name (may raise if read-only).

Parameters:

Name Type Description Default
name str

The flag name.

required
enabled bool

The value to persist.

required

all async

all() -> dict[str, bool]

Return every known flag as a {name: enabled} mapping.

Returns:

Type Description
dict[str, bool]

dict[str, bool]: Every known flag as {name: enabled}.

MemoryFeatureFlagBackend

MemoryFeatureFlagBackend(initial: Mapping[str, bool] | None = None)

In-process feature-flag store (tests, single-worker dev).

Initialize the store.

Parameters:

Name Type Description Default
initial Mapping[str, bool] | None

Seed flags.

None

get async

get(name: str) -> bool | None

Return the flag value, or None when unset.

Parameters:

Name Type Description Default
name str

The flag name.

required

Returns:

Type Description
bool | None

bool | None: The flag value, or None when it is unset.

set async

set(name: str, enabled: bool) -> None

Set the flag value in memory.

Parameters:

Name Type Description Default
name str

The flag name.

required
enabled bool

The value to persist.

required

all async

all() -> dict[str, bool]

Return a copy of every flag.

Returns:

Type Description
dict[str, bool]

dict[str, bool]: Every known flag as {name: enabled}.

EnvFeatureFlagBackend

EnvFeatureFlagBackend(
    *, prefix: str = "FEATURE_", environ: Mapping[str, str] | None = None
)

Read-only feature flags sourced from environment variables.

A flag named new_checkout maps to the env var FEATURE_NEW_CHECKOUT (the prefix plus the upper-cased name). Best used as the static default layer under a :class:CompositeFeatureFlagBackend.

Initialize the backend.

Parameters:

Name Type Description Default
prefix str

Prefix prepended to the upper-cased flag name to form the env var.

'FEATURE_'
environ Mapping[str, str] | None

Environment mapping to read. Defaults to :data:os.environ.

None

get async

get(name: str) -> bool | None

Return the flag value from the environment, or None.

Parameters:

Name Type Description Default
name str

The flag name.

required

Returns:

Type Description
bool | None

bool | None: The flag value, or None when it is unset.

set async

set(name: str, enabled: bool) -> None

Raise — environment-sourced flags are read-only.

Raises:

Type Description
NotImplementedError

Always; env flags are static config.

Parameters:

Name Type Description Default
name str

The flag name.

required
enabled bool

The value to persist.

required

all async

all() -> dict[str, bool]

Return every FEATURE_* env var as a flag mapping.

Returns:

Type Description
dict[str, bool]

dict[str, bool]: Every known flag as {name: enabled}.

RedisFeatureFlagBackend

RedisFeatureFlagBackend(redis: _RedisHashClient, *, key: str = 'feature_flags')

Runtime-toggleable feature flags stored in a single Redis hash.

All flags live as fields of one hash (key), so a toggle is instantly visible to every replica without a redeploy.

Initialize the backend.

Parameters:

Name Type Description Default
redis _RedisHashClient

An async Redis client (e.g. redis.asyncio.Redis or AsyncRedisManager.client). Pass AsyncRedisManager.client_proxy instead when the backend is built before the lifespan connects.

required
key str

The Redis hash key holding every flag.

'feature_flags'

get async

get(name: str) -> bool | None

Return the flag value from the hash, or None when unset.

Parameters:

Name Type Description Default
name str

The flag name.

required

Returns:

Type Description
bool | None

bool | None: The flag value, or None when it is unset.

set async

set(name: str, enabled: bool) -> None

Persist the flag as "1" / "0" in the hash.

Parameters:

Name Type Description Default
name str

The flag name.

required
enabled bool

The value to persist.

required

all async

all() -> dict[str, bool]

Return every field in the hash as a flag mapping.

Returns:

Type Description
dict[str, bool]

dict[str, bool]: Every known flag as {name: enabled}.

CompositeFeatureFlagBackend

CompositeFeatureFlagBackend(backends: Iterable[FeatureFlagBackend])

Layer several backends — first non-None value wins.

The canonical setup is [redis, env]: a runtime Redis override takes precedence, falling back to the static env default. Writes go to the first backend that accepts them (skipping read-only ones).

Initialize the composite.

Parameters:

Name Type Description Default
backends Iterable[FeatureFlagBackend]

Backends in priority order (highest priority first).

required

get async

get(name: str) -> bool | None

Return the first non-None value across the layers.

Parameters:

Name Type Description Default
name str

The flag name.

required

Returns:

Type Description
bool | None

bool | None: The flag value, or None when it is unset.

set async

set(name: str, enabled: bool) -> None

Write to the first backend that accepts writes.

Raises:

Type Description
NotImplementedError

When no layered backend is writable.

Parameters:

Name Type Description Default
name str

The flag name.

required
enabled bool

The value to persist.

required

all async

all() -> dict[str, bool]

Merge every layer, with higher-priority backends winning.

Returns:

Type Description
dict[str, bool]

dict[str, bool]: Every known flag as {name: enabled}.

make_flag_dependency

make_flag_dependency(
    flags: FeatureFlags,
    name: str,
    *,
    enabled: bool = True,
    status_code: int = 404,
    detail: str = "Feature not available",
    code: str = "FEATURE_DISABLED",
) -> Callable[[], Awaitable[None]]

Build a dependency that allows a route only when a flag matches.

Mount it via Depends (or in a router's dependencies=[...]) to gate an endpoint behind a flag. When the flag's state differs from enabled, the dependency raises an :class:AppException rendered through the SDK envelope — 404 by default so a disabled feature simply looks absent.

Parameters:

Name Type Description Default
flags FeatureFlags

The feature-flag service to query.

required
name str

The flag name to check.

required
enabled bool

The flag state the route requires. True (default) allows the route when the flag is on; False allows it only when the flag is off (e.g. a deprecation kill-switch).

True
status_code int

Status code raised when the gate fails. Defaults to 404 (hide the feature); use 403 to signal it exists but is forbidden.

404
detail str

Message for the error envelope.

'Feature not available'
code str

Machine-readable error code for the envelope.

'FEATURE_DISABLED'

Returns:

Type Description
Callable[[], Awaitable[None]]

Callable[[], Awaitable[None]]: An async FastAPI dependency.

coerce_flag

coerce_flag(value: str) -> bool

Interpret a string flag value as a boolean.

Parameters:

Name Type Description Default
value str

The raw value (e.g. an env var or Redis field).

required

Returns:

Name Type Description
bool bool

True for "1"/"true"/"yes"/"on"/"t"/

bool

"y" (case-insensitive), False otherwise.