reflag 0.1.0rc1__tar.gz

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.
Files changed (49) hide show
  1. reflag-0.1.0rc1/.gitattributes +1 -0
  2. reflag-0.1.0rc1/.github/workflows/ci.yml +36 -0
  3. reflag-0.1.0rc1/.github/workflows/publish.yml +91 -0
  4. reflag-0.1.0rc1/.gitignore +11 -0
  5. reflag-0.1.0rc1/LICENSE +21 -0
  6. reflag-0.1.0rc1/PKG-INFO +60 -0
  7. reflag-0.1.0rc1/README.md +46 -0
  8. reflag-0.1.0rc1/examples/basic.py +17 -0
  9. reflag-0.1.0rc1/examples/fastapi_app.py +33 -0
  10. reflag-0.1.0rc1/examples/flag_playground.py +276 -0
  11. reflag-0.1.0rc1/examples/playground/app.js +96 -0
  12. reflag-0.1.0rc1/examples/playground/index.html +55 -0
  13. reflag-0.1.0rc1/examples/playground/style.css +28 -0
  14. reflag-0.1.0rc1/pyproject.toml +45 -0
  15. reflag-0.1.0rc1/src/reflag/__init__.py +29 -0
  16. reflag-0.1.0rc1/src/reflag/_internal/__init__.py +0 -0
  17. reflag-0.1.0rc1/src/reflag/_internal/compatibility.py +167 -0
  18. reflag-0.1.0rc1/src/reflag/_internal/config.py +109 -0
  19. reflag-0.1.0rc1/src/reflag/_internal/core.py +607 -0
  20. reflag-0.1.0rc1/src/reflag/_internal/definitions.py +132 -0
  21. reflag-0.1.0rc1/src/reflag/_internal/evaluation.py +352 -0
  22. reflag-0.1.0rc1/src/reflag/_internal/transport.py +106 -0
  23. reflag-0.1.0rc1/src/reflag/_version.py +1 -0
  24. reflag-0.1.0rc1/src/reflag/async_client.py +412 -0
  25. reflag-0.1.0rc1/src/reflag/client.py +547 -0
  26. reflag-0.1.0rc1/src/reflag/context.py +50 -0
  27. reflag-0.1.0rc1/src/reflag/fallback.py +114 -0
  28. reflag-0.1.0rc1/src/reflag/py.typed +0 -0
  29. reflag-0.1.0rc1/src/reflag/types.py +26 -0
  30. reflag-0.1.0rc1/tests/check_artifact.py +59 -0
  31. reflag-0.1.0rc1/tests/conftest.py +123 -0
  32. reflag-0.1.0rc1/tests/fixtures/evaluator-v2-parity.json +1 -0
  33. reflag-0.1.0rc1/tests/fixtures/generate-evaluator-parity.mjs +216 -0
  34. reflag-0.1.0rc1/tests/fixtures/provenance.json +16 -0
  35. reflag-0.1.0rc1/tests/generate_bootstrap.py +74 -0
  36. reflag-0.1.0rc1/tests/interop_browser.mjs +36 -0
  37. reflag-0.1.0rc1/tests/interop_ingest.mjs +20 -0
  38. reflag-0.1.0rc1/tests/test_clients.py +302 -0
  39. reflag-0.1.0rc1/tests/test_concurrency.py +393 -0
  40. reflag-0.1.0rc1/tests/test_evaluation.py +366 -0
  41. reflag-0.1.0rc1/tests/test_examples.py +31 -0
  42. reflag-0.1.0rc1/tests/test_fallback.py +170 -0
  43. reflag-0.1.0rc1/tests/test_http.py +597 -0
  44. reflag-0.1.0rc1/tests/test_logging.py +222 -0
  45. reflag-0.1.0rc1/tests/test_revalidation.py +312 -0
  46. reflag-0.1.0rc1/tests/test_targeting.py +465 -0
  47. reflag-0.1.0rc1/tests/test_transport.py +123 -0
  48. reflag-0.1.0rc1/tests/typing/consumer.py +48 -0
  49. reflag-0.1.0rc1/uv.lock +759 -0
@@ -0,0 +1 @@
1
+ * text=auto eol=lf
@@ -0,0 +1,36 @@
1
+ name: Python SDK CI
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ test:
12
+ strategy:
13
+ fail-fast: false
14
+ matrix:
15
+ os: [ubuntu-latest]
16
+ python: ['3.11', '3.12', '3.13', '3.14', '3.15']
17
+ include:
18
+ - os: windows-latest
19
+ python: '3.15'
20
+ - os: macos-latest
21
+ python: '3.15'
22
+ runs-on: ${{ matrix.os }}
23
+ steps:
24
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
25
+ - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
26
+ with:
27
+ version: '0.13.8'
28
+ python-version: ${{ matrix.python }}
29
+ enable-cache: true
30
+ - run: uv sync --frozen --group examples
31
+ - run: uv run --frozen --group examples ruff check src tests examples
32
+ - run: uv run --frozen --group examples ruff format --check src tests examples
33
+ - run: uv run --frozen --group examples mypy src/reflag tests/typing/consumer.py examples
34
+ - run: uv run --frozen --group examples pytest -q -W error
35
+ - run: uv build
36
+ - run: uv run --frozen --group examples python tests/check_artifact.py
@@ -0,0 +1,91 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ version:
7
+ description: 'Exact package version to publish (for example, 0.1.0rc1)'
8
+ required: true
9
+ type: string
10
+ publish:
11
+ description: 'Upload to public PyPI (leave unchecked to only build and test)'
12
+ required: true
13
+ type: boolean
14
+ default: false
15
+
16
+ permissions: {}
17
+
18
+ concurrency:
19
+ group: pypi-publish
20
+ cancel-in-progress: false
21
+
22
+ jobs:
23
+ build:
24
+ if: github.ref == 'refs/heads/main'
25
+ runs-on: ubuntu-latest
26
+ timeout-minutes: 15
27
+ permissions:
28
+ contents: read
29
+ steps:
30
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
31
+ - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
32
+ with:
33
+ version: '0.13.8'
34
+ python-version: '3.14'
35
+ enable-cache: true
36
+ - run: uv sync --frozen --group examples
37
+ - name: Verify requested version
38
+ env:
39
+ EXPECTED_VERSION: ${{ inputs.version }}
40
+ run: |
41
+ uv run --frozen --group examples python - <<'PY'
42
+ import os
43
+ from importlib.metadata import version
44
+ from reflag import __version__
45
+ expected = os.environ['EXPECTED_VERSION']
46
+ if version('reflag') != expected or __version__ != expected:
47
+ raise SystemExit('Requested version does not match package metadata and source')
48
+ print(f'Preparing reflag=={expected}')
49
+ PY
50
+ - run: uv run --frozen --group examples ruff check src tests examples
51
+ - run: uv run --frozen --group examples ruff format --check src tests examples
52
+ - run: uv run --frozen --group examples mypy src/reflag tests/typing/consumer.py examples
53
+ - run: uv run --frozen --group examples pytest -q -W error
54
+ - run: uv build --no-sources
55
+ - run: uv run --frozen --group examples python tests/check_artifact.py
56
+ - name: Validate distribution metadata
57
+ run: uvx --from 'twine==7.0.0' twine check --strict dist/*
58
+ - name: Record artifact hashes
59
+ run: sha256sum dist/*.whl dist/*.tar.gz > SHA256SUMS
60
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
61
+ with:
62
+ name: python-distributions
63
+ path: |
64
+ dist/*.whl
65
+ dist/*.tar.gz
66
+ SHA256SUMS
67
+ if-no-files-found: error
68
+ retention-days: 14
69
+
70
+ publish:
71
+ needs: build
72
+ if: inputs.publish
73
+ runs-on: ubuntu-latest
74
+ timeout-minutes: 10
75
+ permissions:
76
+ id-token: write
77
+ environment:
78
+ name: pypi
79
+ url: https://pypi.org/p/reflag
80
+ steps:
81
+ - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
82
+ with:
83
+ name: python-distributions
84
+ path: release
85
+ - name: Verify artifact hashes
86
+ working-directory: release
87
+ run: sha256sum --check SHA256SUMS
88
+ - name: Publish tested distributions
89
+ uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
90
+ with:
91
+ packages-dir: release/dist/
@@ -0,0 +1,11 @@
1
+ .venv/
2
+ .env
3
+ .env.*
4
+ !.env.example
5
+ __pycache__/
6
+ *.py[cod]
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
10
+ dist/
11
+ .reflag/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bucket ApS
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.
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.5
2
+ Name: reflag
3
+ Version: 0.1.0rc1
4
+ Summary: Typed Python server SDK for Reflag protocol-v2 feature flags
5
+ Project-URL: Homepage, https://reflag.com
6
+ Project-URL: Repository, https://github.com/reflagcom/python-sdk
7
+ Author: Reflag
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Requires-Python: >=3.11
11
+ Requires-Dist: httpx-sse<1,>=0.4
12
+ Requires-Dist: httpx<1,>=0.28
13
+ Description-Content-Type: text/markdown
14
+
15
+ # Reflag Python SDK
16
+
17
+ Typed, server-side Boolean and JSON feature flags.
18
+
19
+ ## Installation
20
+
21
+ Install the release candidate from PyPI:
22
+
23
+ ```bash
24
+ pip install "reflag==0.1.0rc1"
25
+ ```
26
+
27
+ This is a preview release; the API may change before 0.1.0.
28
+
29
+ ## Support
30
+
31
+ - Python **3.11+**, including tested Python **3.14**.
32
+ - Synchronous and native asyncio clients; the source distribution includes a FastAPI lifespan example at `examples/fastapi_app.py`.
33
+ - Pydantic v2: convert context models with `model_dump(mode="json")` and validate returned JSON with `model_validate()`.
34
+ - FastMCP integration coverage is planned, but not yet verified.
35
+
36
+ ## Getting started
37
+
38
+ Set your server-side secret key in the application environment:
39
+
40
+ ```bash
41
+ export REFLAG_SECRET_KEY="your-server-secret-key"
42
+ ```
43
+
44
+ ```python
45
+ from reflag import Client
46
+
47
+ with Client() as client:
48
+ flags = client.bind({"user": {"id": "user-123"}, "company": {"id": "company-123"}})
49
+ enabled = flags.get_flag("my-flag", default=False)
50
+ settings = flags.get_flag("settings", default={"theme": "light"})
51
+ ```
52
+
53
+ Replace the flag keys and IDs with your own. Reuse one client per application worker;
54
+ initialization loads definitions, and subsequent flag reads are local and in-memory.
55
+
56
+ For async applications, use `async with AsyncClient()` in the application lifespan.
57
+ Flag reads remain synchronous: do **not** await `get_flag()`.
58
+
59
+ Context/check telemetry is enabled by default; use `client.bind(context, telemetry=False)`
60
+ to opt out. Keep the secret key on the server, never in browser code.
@@ -0,0 +1,46 @@
1
+ # Reflag Python SDK
2
+
3
+ Typed, server-side Boolean and JSON feature flags.
4
+
5
+ ## Installation
6
+
7
+ Install the release candidate from PyPI:
8
+
9
+ ```bash
10
+ pip install "reflag==0.1.0rc1"
11
+ ```
12
+
13
+ This is a preview release; the API may change before 0.1.0.
14
+
15
+ ## Support
16
+
17
+ - Python **3.11+**, including tested Python **3.14**.
18
+ - Synchronous and native asyncio clients; the source distribution includes a FastAPI lifespan example at `examples/fastapi_app.py`.
19
+ - Pydantic v2: convert context models with `model_dump(mode="json")` and validate returned JSON with `model_validate()`.
20
+ - FastMCP integration coverage is planned, but not yet verified.
21
+
22
+ ## Getting started
23
+
24
+ Set your server-side secret key in the application environment:
25
+
26
+ ```bash
27
+ export REFLAG_SECRET_KEY="your-server-secret-key"
28
+ ```
29
+
30
+ ```python
31
+ from reflag import Client
32
+
33
+ with Client() as client:
34
+ flags = client.bind({"user": {"id": "user-123"}, "company": {"id": "company-123"}})
35
+ enabled = flags.get_flag("my-flag", default=False)
36
+ settings = flags.get_flag("settings", default={"theme": "light"})
37
+ ```
38
+
39
+ Replace the flag keys and IDs with your own. Reuse one client per application worker;
40
+ initialization loads definitions, and subsequent flag reads are local and in-memory.
41
+
42
+ For async applications, use `async with AsyncClient()` in the application lifespan.
43
+ Flag reads remain synchronous: do **not** await `get_flag()`.
44
+
45
+ Context/check telemetry is enabled by default; use `client.bind(context, telemetry=False)`
46
+ to opt out. Keep the secret key on the server, never in browser code.
@@ -0,0 +1,17 @@
1
+ """Run with REFLAG_SECRET_KEY set, or REFLAG_OFFLINE=true for a network-free demo."""
2
+
3
+ from reflag import Client
4
+
5
+
6
+ def main() -> None:
7
+ with Client() as client:
8
+ bound = client.bind({"user": {"id": "example-user"}, "company": {"id": "example-company"}})
9
+ print("Dashboard enabled:", bound.get_flag("new-dashboard"))
10
+ print(
11
+ "Model:", bound.get_flag("model-config", default={"name": "small", "max_tokens": 1000})
12
+ )
13
+ bound.track("dashboard-opened", attributes={"surface": "example"})
14
+
15
+
16
+ if __name__ == "__main__":
17
+ main()
@@ -0,0 +1,33 @@
1
+ """Optional example: uv run --with fastapi --with uvicorn uvicorn examples.fastapi_app:app.
2
+
3
+ Set REFLAG_SECRET_KEY, or REFLAG_OFFLINE=true. No framework dependency is required
4
+ by the reflag package. Construct the client in lifespan, after worker fork.
5
+ """
6
+
7
+ from collections.abc import AsyncIterator
8
+ from contextlib import asynccontextmanager
9
+ from typing import cast
10
+
11
+ from fastapi import FastAPI, Request
12
+
13
+ from reflag import AsyncClient
14
+
15
+
16
+ @asynccontextmanager
17
+ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
18
+ async with AsyncClient() as client:
19
+ app.state.reflag = client
20
+ yield
21
+
22
+
23
+ app = FastAPI(lifespan=lifespan)
24
+
25
+
26
+ @app.get("/dashboard/{user_id}")
27
+ async def dashboard(user_id: str, request: Request) -> dict[str, object]:
28
+ client = cast(AsyncClient, request.app.state.reflag)
29
+ bound = client.bind({"user": {"id": user_id}})
30
+ enabled = bound.get_flag("new-dashboard") # Local read; deliberately no await.
31
+ if enabled:
32
+ await bound.track("dashboard-opened")
33
+ return {"enabled": enabled, "model": bound.get_flag("model-config", default={"name": "small"})}
@@ -0,0 +1,276 @@
1
+ """Local flag playground: uv run --group examples python examples/flag_playground.py.
2
+
3
+ Uses the remote API with server-side SSE updates. Set REFLAG_SECRET_KEY and optionally
4
+ REFLAG_API_BASE_URL; SSE uses /sse/server on that same base URL.
5
+ Set REFLAG_PLAYGROUND_HOST=0.0.0.0 for LAN/Tailscale access. There is no authentication
6
+ or Host allowlist; use only a trusted LAN or VPN.
7
+ """
8
+
9
+ import asyncio
10
+ import json
11
+ import logging
12
+ import os
13
+ from collections import Counter
14
+ from collections.abc import AsyncIterator, Awaitable, Callable
15
+ from contextlib import asynccontextmanager
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import httpx
20
+ from fastapi import FastAPI, HTTPException, Request, Response
21
+ from fastapi.responses import FileResponse, JSONResponse
22
+ from pydantic import BaseModel, ConfigDict, Field
23
+ from starlette.staticfiles import StaticFiles
24
+
25
+ from reflag import AsyncClient
26
+
27
+ ASSETS = Path(__file__).with_name("playground")
28
+ # Inherit the server's handlers/level for both the script and Uvicorn CLI.
29
+ logger = logging.getLogger("uvicorn.error.playground")
30
+
31
+
32
+ class EvaluationRequest(BaseModel):
33
+ model_config = ConfigDict(extra="forbid", strict=True)
34
+ flag_key: str = Field(min_length=1)
35
+ context: dict[str, Any] = Field(default_factory=dict)
36
+ default: Any = None
37
+ refresh: bool = True
38
+ telemetry: bool = True
39
+
40
+
41
+ def create_app() -> FastAPI:
42
+ if not os.getenv("REFLAG_PLAYGROUND_HOST", "127.0.0.1").strip():
43
+ raise ValueError("REFLAG_PLAYGROUND_HOST must not be empty")
44
+
45
+ @asynccontextmanager
46
+ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
47
+ secret_key = os.getenv("REFLAG_SECRET_KEY")
48
+ if not secret_key:
49
+ raise ValueError("Set REFLAG_SECRET_KEY before starting the playground")
50
+ if os.getenv("REFLAG_OFFLINE", "false").lower() not in {"false", "0", "off"}:
51
+ raise ValueError("Unset REFLAG_OFFLINE; the playground only supports live requests")
52
+ api_base_url = os.getenv("REFLAG_API_BASE_URL", "https://front.reflag.com").rstrip("/")
53
+ app.state.last_fetch = None
54
+ app.state.fetch_count = 0
55
+ app.state.evaluation_lock = asyncio.Lock()
56
+ app.state.delivery = {
57
+ "bulk_requests": 0,
58
+ "acknowledged_batches": 0,
59
+ "warning_batches": 0,
60
+ "events_attempted": 0,
61
+ }
62
+ app.state.last_delivery = None
63
+
64
+ async def on_request(request: httpx.Request) -> None:
65
+ if request.method == "GET" and request.url.path.endswith("/flags"):
66
+ app.state.fetch_count += 1
67
+ app.state.last_fetch = {
68
+ "status_code": None,
69
+ "conditional": "if-none-match" in request.headers,
70
+ "etag": None,
71
+ }
72
+ logger.info(
73
+ "Refreshing /flags (request=%d, conditional=%s, target_version=%s)",
74
+ app.state.fetch_count,
75
+ app.state.last_fetch["conditional"],
76
+ request.url.params.get("waitForVersion"),
77
+ )
78
+ elif request.method == "GET" and request.url.path.endswith("/sse/server"):
79
+ logger.info("Connecting to Reflag SSE stream")
80
+ elif request.method == "POST" and request.url.path.endswith("/bulk"):
81
+ events = json.loads(request.content)
82
+ app.state.delivery["bulk_requests"] += 1
83
+ app.state.delivery["events_attempted"] += len(events)
84
+ # Counts only: never reflect contexts, credentials or event payloads.
85
+ app.state.last_delivery = {
86
+ "status_code": None,
87
+ "acknowledged": False,
88
+ "warning": False,
89
+ "validation_error_count": 0,
90
+ "event_count": len(events),
91
+ "event_types": dict(Counter(event["type"] for event in events)),
92
+ }
93
+
94
+ async def on_response(response: httpx.Response) -> None:
95
+ request = response.request
96
+ if request.method == "GET" and request.url.path.endswith("/flags"):
97
+ app.state.last_fetch = {
98
+ "status_code": response.status_code,
99
+ "conditional": "if-none-match" in request.headers,
100
+ "etag": response.headers.get("etag"),
101
+ }
102
+ logger.info(
103
+ "Flag refresh received HTTP %d (conditional=%s)",
104
+ response.status_code,
105
+ app.state.last_fetch["conditional"],
106
+ )
107
+ elif request.method == "GET" and request.url.path.endswith("/sse/server"):
108
+ logger.info("Reflag SSE connection received HTTP %d", response.status_code)
109
+ elif request.method == "POST" and request.url.path.endswith("/bulk"):
110
+ delivery = app.state.last_delivery
111
+ delivery["status_code"] = response.status_code
112
+ if not response.is_success:
113
+ return
114
+ await response.aread()
115
+ try:
116
+ data = response.json()
117
+ except ValueError:
118
+ return
119
+ if not isinstance(data, dict) or data.get("success") is not True:
120
+ return
121
+ delivery["acknowledged"] = True
122
+ app.state.delivery["acknowledged_batches"] += 1
123
+ errors = data.get("validationErrors", [])
124
+ delivery["validation_error_count"] = len(errors) if isinstance(errors, list) else 0
125
+ delivery["warning"] = bool(data.get("warning") or data.get("error") or errors)
126
+ if delivery["warning"]:
127
+ app.state.delivery["warning_batches"] += 1
128
+ logger.warning(
129
+ "Reflag bulk response reported warnings (%d validation errors)",
130
+ delivery["validation_error_count"],
131
+ )
132
+
133
+ hooks: dict[str, list[Callable[..., Awaitable[None]]]] = {
134
+ "request": [on_request],
135
+ "response": [on_response],
136
+ }
137
+ # Keep the long-lived SSE stream in a separate pool from flags/telemetry.
138
+ async with (
139
+ httpx.AsyncClient(event_hooks=hooks) as http,
140
+ httpx.AsyncClient(event_hooks=hooks) as sse_http,
141
+ ):
142
+ client = AsyncClient(
143
+ http_client=http,
144
+ sse_http_client=sse_http,
145
+ secret_key=secret_key,
146
+ api_base_url=api_base_url,
147
+ push_url=f"{api_base_url}/sse/server",
148
+ logger=logger,
149
+ offline=False,
150
+ sync_mode="push",
151
+ min_refresh_interval=0,
152
+ fetch_retries=0,
153
+ fetch_timeout=5,
154
+ )
155
+ client.clear_flag_overrides() # Test definitions, never environment overrides.
156
+ async with client:
157
+ app.state.reflag = client
158
+ logger.info(
159
+ "SDK initialized (status=%s, accepted_version=%s, sync_mode=push/SSE)",
160
+ client.status,
161
+ client.flag_state_version,
162
+ )
163
+ yield
164
+
165
+ app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
166
+
167
+ async def check_request(request: Request) -> Response | None:
168
+ if request.method == "POST":
169
+ origin = request.headers.get("origin")
170
+ if origin is not None and origin != str(request.base_url).rstrip("/"):
171
+ return JSONResponse({"detail": "Cross-origin requests are not permitted"}, 403)
172
+ if request.headers.get("content-type", "").split(";")[0].strip() != "application/json":
173
+ return JSONResponse({"detail": "Send application/json"}, 415)
174
+ if len(await request.body()) > 65_536:
175
+ return JSONResponse({"detail": "Request exceeds 64 KiB"}, 413)
176
+ return None
177
+
178
+ @app.middleware("http")
179
+ async def request_guards(
180
+ request: Request, call_next: Callable[[Request], Awaitable[Response]]
181
+ ) -> Response:
182
+ response = await check_request(request)
183
+ if response is None:
184
+ response = await call_next(request)
185
+ response.headers["Cache-Control"] = "no-store"
186
+ response.headers["X-Content-Type-Options"] = "nosniff"
187
+ response.headers["Content-Security-Policy"] = (
188
+ "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; "
189
+ "base-uri 'none'; frame-ancestors 'none'; form-action 'self'"
190
+ )
191
+ return response
192
+
193
+ def status() -> dict[str, Any]:
194
+ client = app.state.reflag
195
+ return {
196
+ "mode": "live",
197
+ "client_status": client.status,
198
+ "flag_state_version": client.flag_state_version,
199
+ "flags": [flag["key"] for flag in client.get_flag_definitions()["flags"]],
200
+ "fetch_count": app.state.fetch_count,
201
+ "last_fetch": app.state.last_fetch,
202
+ "telemetry": {**app.state.delivery, "last_delivery": app.state.last_delivery},
203
+ }
204
+
205
+ @app.get("/")
206
+ async def index() -> FileResponse:
207
+ return FileResponse(ASSETS / "index.html")
208
+
209
+ @app.get("/api/status")
210
+ async def get_status() -> dict[str, Any]:
211
+ return status()
212
+
213
+ @app.post("/evaluate")
214
+ async def evaluate(body: EvaluationRequest) -> dict[str, Any]:
215
+ client = app.state.reflag
216
+ # Serialize this smoke tool's evaluations/flushes to keep delivery deltas distinct.
217
+ async with app.state.evaluation_lock:
218
+ try:
219
+ context = client.bind(body.context, telemetry=False).context
220
+ if body.refresh:
221
+ await client.refresh_flags()
222
+ logger.info(
223
+ "Flag refresh finished (status=%s, accepted_version=%s)",
224
+ client.status,
225
+ client.flag_state_version,
226
+ )
227
+ metadata = status()
228
+ if client.status != "ready":
229
+ raise HTTPException(
230
+ 503, "No valid definitions received; inspect the server logs"
231
+ )
232
+ if body.flag_key not in metadata.pop("flags"):
233
+ raise HTTPException(404, "Flag key is not in the accepted definitions")
234
+ before = app.state.delivery.copy()
235
+ value = client.get_flag(
236
+ body.flag_key, context=context, default=body.default, telemetry=body.telemetry
237
+ )
238
+ if body.telemetry:
239
+ await client.flush()
240
+ except (TypeError, ValueError):
241
+ raise HTTPException(422, "Invalid context or default JSON value") from None
242
+ delivery = {key: count - before[key] for key, count in app.state.delivery.items()}
243
+ outcome = "disabled"
244
+ if body.telemetry:
245
+ if not delivery["bulk_requests"]:
246
+ outcome = "deduplicated_or_empty"
247
+ elif delivery["acknowledged_batches"] != delivery["bulk_requests"]:
248
+ outcome = "failed"
249
+ elif delivery["warning_batches"]:
250
+ outcome = "warning"
251
+ else:
252
+ outcome = "acknowledged"
253
+ metadata["telemetry"] = {
254
+ "enabled": body.telemetry,
255
+ "outcome": outcome,
256
+ **delivery,
257
+ "last_delivery": app.state.last_delivery if delivery["bulk_requests"] else None,
258
+ }
259
+ return {"flag_key": body.flag_key, "value": value, **metadata}
260
+
261
+ app.mount("/static", StaticFiles(directory=ASSETS), name="static")
262
+ return app
263
+
264
+
265
+ app = create_app()
266
+
267
+ if __name__ == "__main__":
268
+ import uvicorn
269
+
270
+ logging.basicConfig(level=logging.INFO, format="%(name)s %(levelname)s %(message)s")
271
+ uvicorn.run(
272
+ app,
273
+ host=os.getenv("REFLAG_PLAYGROUND_HOST", "127.0.0.1").strip(),
274
+ port=8000,
275
+ proxy_headers=False,
276
+ )