diff --git a/README.md b/README.md index 2315233..b2f951f 100644 --- a/README.md +++ b/README.md @@ -17,32 +17,99 @@ pip install reflag ## Getting started -Set your server-side secret key in the application environment: +Set your server-side secret key: ```bash export REFLAG_SECRET_KEY="your-server-secret-key" ``` +Create **one client per application worker** and reuse it across requests. Initialize +it at startup and close it at shutdown. The `with` block below represents that +application lifetime, not a single request. + ```python from reflag import Client with Client() as client: - flags = client.bind({"user": {"id": "user-123"}, "company": {"id": "company-123"}}) + flags = client.bind( + { + "user": {"id": "user-123"}, + "company": {"id": "company-123"}, + } + ) + + # Boolean flag, with False as the fallback. enabled = flags.get_flag("my-flag") + + # JSON flag, with an object as the fallback. settings = flags.get_flag("settings", default={"theme": "light"}) ``` -Omitting `default` is equivalent to `default=False` and returns a `bool`. +Use `client.bind(...)` for each request's user/company context; it reuses the +underlying client. + +Initialization loads flag definitions. Subsequent flag reads are local and in-memory. + +### Async applications + +Use `AsyncClient` with `async with` in your application's lifespan. Flag reads remain +synchronous: call `flags.get_flag(...)` without `await`. See the [FastAPI example](#fastapi) +for a complete web application. + +### Telemetry + +Context and flag-check telemetry is enabled by default. To disable it for a bound +context, use `client.bind(context, telemetry=False)`. + +Keep your secret key on the server, never in browser code. + +## FastAPI + +Install the SDK and web server, then set your server-side secret key: + +```bash +pip install reflag fastapi uvicorn +export REFLAG_SECRET_KEY="your-server-secret-key" +``` + +Create `app.py`: + +```python +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +from fastapi import FastAPI, Request + +from reflag import AsyncClient + -Replace the flag keys and IDs with your own. +@asynccontextmanager +async def lifespan(app: FastAPI) -> AsyncIterator[None]: + # One shared client per worker, initialized at startup and closed at shutdown. + async with AsyncClient() as client: + app.state.reflag = client + yield -Create and initialize **one client per application worker** at startup, reuse it -across requests, and close it at shutdown. Do not create a new client for each request -or flag check. Use `client.bind(...)` for request-specific user/company context. -Initialization loads definitions; subsequent flag reads are local and in-memory. -For async applications, use `async with AsyncClient()` in the application lifespan. -Flag reads remain synchronous: do **not** await `get_flag()`. +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 + flags = client.bind({"company": {"id": company_id}}) + + # Boolean flag; defaults to False. + enabled = flags.get_flag("new-dashboard") + + # JSON flag with an object fallback. + settings = flags.get_flag("dashboard-settings", default={"theme": "light"}) + + return { + "dashboard": "new" if enabled else "classic", + "settings": settings, + } +``` -Context/check telemetry is enabled by default; use `client.bind(context, telemetry=False)` -to opt out. Keep the secret key on the server, never in browser code. +The shared client keeps flag definitions up to date. Flag reads are local and +synchronous, so `get_flag()` does not need `await`. diff --git a/tests/test_examples.py b/tests/test_examples.py index 4f70e0a..8f91ca2 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -1,11 +1,21 @@ import importlib.util import runpy from pathlib import Path +from typing import Any import httpx import pytest +def _load_readme_example(heading: str, module_name: str) -> dict[str, Any]: + readme = Path(__file__).parents[1] / "README.md" + section = readme.read_text(encoding="utf-8").split(f"## {heading}\n", 1)[1] + code = section.split("```python\n", 1)[1].split("```", 1)[0] + namespace: dict[str, Any] = {"__name__": module_name} + exec(compile(code, str(readme), "exec"), namespace) + return namespace + + def test_basic_example_is_runnable_offline(monkeypatch, capsys): monkeypatch.setenv("REFLAG_OFFLINE", "true") runpy.run_path(str(Path(__file__).parents[1] / "examples/basic.py"), run_name="__main__") @@ -29,3 +39,45 @@ async def test_fastapi_lifespan_and_real_endpoint(monkeypatch): assert response.json() == {"enabled": False, "model": {"name": "small"}} assert module.app.state.reflag.status == "offline" assert module.app.state.reflag.status == "closed" + + +def test_readme_getting_started_is_runnable_offline(monkeypatch): + monkeypatch.setenv("REFLAG_OFFLINE", "true") + namespace = _load_readme_example("Getting started", "readme_getting_started_example") + assert namespace["enabled"] is False + assert namespace["settings"] == {"theme": "light"} + assert namespace["client"].status == "closed" + + +async def test_readme_fastapi_lifespan_and_endpoint(monkeypatch): + pytest.importorskip("fastapi") + monkeypatch.setenv("REFLAG_OFFLINE", "true") + namespace = _load_readme_example("FastAPI", "readme_fastapi_example") + app = namespace["app"] + + async with app.router.lifespan_context(app): + client = app.state.reflag + assert client.status == "offline" + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://asgi.test" + ) as http: + response = await http.get("/companies/company-123/dashboard") + assert response.status_code == 200 + assert response.json() == {"dashboard": "classic", "settings": {"theme": "light"}} + + client.set_flag_overrides( + lambda context: { + "new-dashboard": context["company"]["id"] == "company-123", + "dashboard-settings": {"theme": "dark"}, + } + ) + response = await http.get("/companies/company-123/dashboard") + assert response.status_code == 200 + assert response.json() == {"dashboard": "new", "settings": {"theme": "dark"}} + + response = await http.get("/companies/company-456/dashboard") + assert response.status_code == 200 + assert response.json() == {"dashboard": "classic", "settings": {"theme": "dark"}} + assert app.state.reflag is client + + assert client.status == "closed"