diff --git a/README.md b/README.md index e4cbdaa..8e8d667 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,6 @@ Typed, server-side Boolean and JSON feature flags. -Remote config is not supported by this SDK. Use multivariate flags for configuration -values instead. - ## Installation Install from PyPI: @@ -30,14 +27,21 @@ Create **one client per application worker** and reuse it across requests. Initi it at startup and close it at shutdown. The `with` block below represents that application lifetime, not a single request. +For each request, call `client.bind(...)` with that request's user and company. Binding +is cheap and reuses the shared client. + ```python from reflag import Client with Client() as client: flags = client.bind( { - "user": {"id": "user-123"}, - "company": {"id": "company-123"}, + "user": {"id": "user-123", "email": "ada@example.com"}, + "company": { + "id": "company-123", + "name": "Acme", + "attributes": {"plan": "enterprise"}, + }, } ) @@ -48,10 +52,29 @@ with Client() as client: settings = flags.get_flag("settings", default={"theme": "light"}) ``` -Use `client.bind(...)` for each request's user/company context; it reuses the -underlying client. +Targeting rules match on `id`, `name`, `email` and any `attributes`. Attributes are +flattened, so `attributes={"plan": "enterprise"}` is matched as the company's `plan`. + +### Defaults and types + +`get_flag()` returns your `default` (or `False` if you don't pass one) when: + +- the flag doesn't exist, for example because of a typo in the key; +- the flag's value has a different JSON type from the default (a warning is logged); +- flag definitions haven't loaded. + +The default also sets the return type for type checkers: a `bool` default returns `bool`, +a `dict` default returns `dict[str, JSONValue]`, and `str`, number and `list` defaults +work the same way. + +### Startup and status + +Initialization waits for the first flag definitions to load. Subsequent flag reads are +local and in-memory. -Initialization loads flag definitions. Subsequent flag reads are local and in-memory. +If Reflag can't be reached at startup, the client doesn't raise. Instead, +`client.status` is `"degraded"` and flag reads return their defaults. Check +`client.status` in a health check if you need to know whether definitions are loaded. ### Async applications @@ -59,6 +82,16 @@ Use `AsyncClient` with `async with` in your application's lifespan. Flag reads r synchronous: call `flags.get_flag(...)` without `await`. See the [FastAPI example](#fastapi) for a complete web application. +### Forking servers and workers + +A client can only be used in the process that created it; using it after a fork raises +`RuntimeError`. This affects gunicorn (especially with `--preload`), uWSGI, Celery's +prefork pool and `multiprocessing`. + +Create the client inside each worker after it forks, for example in gunicorn's +`post_fork` hook or Celery's `worker_process_init` signal, and close it when the worker +exits. ASGI lifespans, as in the [FastAPI example](#fastapi), already run once per worker. + ### Telemetry Context and flag-check telemetry is enabled by default. To disable it for a bound @@ -66,6 +99,66 @@ context, use `client.bind(context, telemetry=False)`. Keep your secret key on the server, never in browser code. +## Testing + +In offline mode the client needs no secret key, makes no network requests and sends no +telemetry. Flags return their defaults unless you override them. Set +`REFLAG_OFFLINE=true` so that application code calling `Client()` works unchanged, or pass +`offline=True`. + +```python +from reflag import Client + +with Client( + offline=True, + flag_overrides={"new-dashboard": True, "dashboard-settings": {"theme": "dark"}}, +) as client: + flags = client.bind({"company": {"id": "company-123"}}) + assert flags.get_flag("new-dashboard") is True + + # Replace the base overrides. + client.set_flag_overrides({"new-dashboard": False}) + assert flags.get_flag("new-dashboard") is False + + # Layer scoped overrides on top; they're removed when the block exits. + with client.override_flags( + lambda context: {"new-dashboard": context["company"]["id"] == "company-123"} + ): + assert flags.get_flag("new-dashboard") is True + + client.clear_flag_overrides() + assert flags.get_flag("new-dashboard") is False +``` + +Overrides map flag keys to JSON values. They can also be a function that receives the +evaluation context and returns that map. Scoped overrides from `override_flags()` take +precedence over base overrides and apply only in the current thread or async task. + +Overrides apply **after evaluation**, so overriding a flag doesn't change the results of +other flags that depend on it. They also work in online mode, for example during local +development. + +## Bootstrapping browser clients + +To render a page with flags already evaluated, get bootstrap state on the server and pass +the whole object to the Reflag Browser SDK's `bootstrappedState` option. This requires +Browser SDK v2 or a framework SDK built on it. + +```python +import json + +from reflag import Client + +with Client() as client: + flags = client.bind({"user": {"id": "user-123"}, "company": {"id": "company-123"}}) + bootstrap = flags.get_flags_for_bootstrap() + bootstrap_json = json.dumps(bootstrap) # Embed this in the page. +``` + +Bootstrap state includes only flags that aren't marked secret in Reflag, plus the context +you bound. Bind only context that is safe to show in the browser. Getting bootstrap +state doesn't record flag checks. + ## FastAPI Install the SDK and web server, then set your server-side secret key: @@ -99,7 +192,7 @@ app = FastAPI(lifespan=lifespan) @app.get("/companies/{company_id}/dashboard") async def dashboard(company_id: str, request: Request) -> dict[str, object]: - client: AsyncClient = request.app.state.reflag + client: AsyncClient = request.app.state.reflag # app.state is untyped. flags = client.bind({"company": {"id": company_id}}) # Boolean flag; defaults to False. diff --git a/tests/test_examples.py b/tests/test_examples.py index 8f91ca2..70dbe39 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -1,4 +1,5 @@ import importlib.util +import json import runpy from pathlib import Path from typing import Any @@ -49,6 +50,22 @@ def test_readme_getting_started_is_runnable_offline(monkeypatch): assert namespace["client"].status == "closed" +def test_readme_testing_example_runs_without_secret_key(monkeypatch): + monkeypatch.delenv("REFLAG_SECRET_KEY", raising=False) + monkeypatch.delenv("REFLAG_OFFLINE", raising=False) + namespace = _load_readme_example("Testing", "readme_testing_example") + assert namespace["client"].status == "closed" + + +def test_readme_bootstrap_example_is_runnable_offline(monkeypatch): + monkeypatch.setenv("REFLAG_OFFLINE", "true") + namespace = _load_readme_example("Bootstrapping browser clients", "readme_bootstrap_example") + bootstrap = namespace["bootstrap"] + assert bootstrap["protocolVersion"] == 2 + assert bootstrap["context"] == {"user": {"id": "user-123"}, "company": {"id": "company-123"}} + assert json.loads(namespace["bootstrap_json"]) == bootstrap + + async def test_readme_fastapi_lifespan_and_endpoint(monkeypatch): pytest.importorskip("fastapi") monkeypatch.setenv("REFLAG_OFFLINE", "true")