diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d3db83bd..7a10b4db 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -195,6 +195,7 @@ jobs: cargo test -p server --test security_remediation -- --nocapture cargo test -p server --test integration_test_message -- --nocapture cargo test -p server --test analytics_hardening -- --nocapture + cargo test -p server --test propose_scope -- --nocapture # The server's own tests that need PostgreSQL and Redis (they skip in # the Rust tests job, which has neither): the scheduler, analytics @@ -217,6 +218,28 @@ jobs: - name: SSE fault-injection tests run: cargo test -p server --test sse_faults -- --nocapture + # @checkgate/mcp-server against the real server binary built above: an + # agent with a propose token proposes, the server queues it, a different + # person approves, the agent reads it back. Also prints the measured + # MCP-over-stdio overhead versus direct HTTP. + - uses: actions/setup-node@v5 + with: + node-version: 22 + + - name: MCP server end-to-end test + working-directory: integrations/mcp-server + env: + PGPASSWORD: postgres + CHECKGATE_E2E_SERVER_BIN: ${{ github.workspace }}/target/debug/server + CHECKGATE_E2E_DATABASE_URL: postgres://postgres:postgres@localhost:5432/checkgate_mcp_e2e + CHECKGATE_E2E_REDIS_URL: redis://localhost:6379 + CHECKGATE_REQUIRE_MCP_E2E: "1" + run: | + npm ci --ignore-scripts + test -x "$CHECKGATE_E2E_SERVER_BIN" || cargo build -p server + psql -h localhost -U postgres -c 'DROP DATABASE IF EXISTS checkgate_mcp_e2e' -c 'CREATE DATABASE checkgate_mcp_e2e' + node --test test/e2e.test.js + - name: Upload reliability artifacts if: always() uses: actions/upload-artifact@v6 @@ -314,6 +337,19 @@ jobs: with: channel: stable + # The Python SDK joins the live suite: scripts/sdk-live-e2e.sh expects + # the package installed in sdks/python/.venv. + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Python SDK for the live suite + run: | + python -m venv sdks/python/.venv + sdks/python/.venv/bin/pip install "maturin>=1.9.4,<2" + sdks/python/.venv/bin/maturin build --release --manifest-path sdks/python/Cargo.toml --out dist-python + sdks/python/.venv/bin/pip install dist-python/*.whl + - name: Live end-to-end, every SDK env: PGPASSWORD: postgres @@ -420,6 +456,33 @@ jobs: test "$code" -eq 3 node -e 'const r = JSON.parse(require("fs").readFileSync(process.argv[1], "utf8")); if (r.status !== "out_of_date" || r.findings[0].id !== "typegen.out_of_date") process.exit(1)' "$RUNNER_TEMP/report.json" + # --------------------------------------------------------------------------- + # MCP server — @checkgate/mcp-server unit, schema and stdio lifecycle tests + # against a fake API (the e2e run against a real server is in + # server-integration). + # --------------------------------------------------------------------------- + mcp-server: + name: MCP server tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-node@v5 + with: + node-version: 22 + + - name: Install dependencies (lockfile, no install scripts) + working-directory: integrations/mcp-server + run: npm ci --ignore-scripts + + - name: Run tests + working-directory: integrations/mcp-server + run: npm test + + - name: Audit production dependencies + working-directory: integrations/mcp-server + run: npm audit --omit=dev --audit-level=high + # --------------------------------------------------------------------------- # Edge — @checkgate/edge evaluator tests (zero deps, Node's built-in runner) # --------------------------------------------------------------------------- @@ -477,6 +540,90 @@ jobs: working-directory: sdks/nodejs run: node --test + # --------------------------------------------------------------------------- + # Node SDK with the REAL native engine (sdk-node above uses the stand-in): + # the shared evaluation vectors, and the OpenFeature provider against the + # real OpenFeature SDK and a real SSE stream. Every Node.js line in LTS + # (22 and 24 maintenance, 26 active); 20 reached end of life on 2026-04-30. + # --------------------------------------------------------------------------- + sdk-node-native: + name: Node SDK (native) + OpenFeature provider (Node ${{ matrix.node }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: [22, 24, 26] + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-node@v5 + with: + node-version: ${{ matrix.node }} + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + + - name: Cache Rust build artifacts + uses: Swatinem/rust-cache@v2 + + - name: Build the native addon + working-directory: sdks/nodejs + run: npm ci && npm run build:debug + + - name: Node SDK tests (real engine, shared vectors) + working-directory: sdks/nodejs + run: node --test + + - name: OpenFeature provider — install, typecheck, test + working-directory: sdks/openfeature-provider + run: npm ci && npm run typecheck && npm test + + # --------------------------------------------------------------------------- + # Node framework integrations — @checkgate/node-integrations (Express, + # Fastify, NestJS) over the REAL @checkgate/node and its native addon, with + # sdks/conformance/fault-server.mjs as the Checkgate server. Every Node.js + # line in LTS (22 and 24 maintenance, 26 active); 20 reached end of life on + # 2026-04-30. + # --------------------------------------------------------------------------- + node-integrations: + name: Node integrations (Node ${{ matrix.node }}) + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + node: [22, 24, 26] + steps: + - uses: actions/checkout@v5 + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + + - name: Cache Rust build artifacts + uses: Swatinem/rust-cache@v2 + + - uses: actions/setup-node@v5 + with: + node-version: ${{ matrix.node }} + + - name: Build the Node SDK native addon + working-directory: sdks/nodejs + run: | + npm ci + npm run build:debug + + - name: Install dependencies + working-directory: sdks/node-integrations + run: npm ci + + - name: Type definitions compile + working-directory: sdks/node-integrations + run: npm run typecheck + + - name: Run tests (adapters, examples, core) + working-directory: sdks/node-integrations + run: npm test + # --------------------------------------------------------------------------- # Web + React Native SDKs — client-logic unit tests (vitest; the WASM core is # stubbed for web, the JSI bridge faked for RN — no native/WASM build needed) @@ -582,6 +729,60 @@ jobs: path: conformance-traces retention-days: 30 + sdk-python: + name: Python SDK tests (${{ matrix.python }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # The wheel is abi3 (CPython 3.11+): test the oldest and the newest. + python: ["3.11", "3.13"] + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + + - name: Cache Rust build artifacts + uses: Swatinem/rust-cache@v2 + + - uses: actions/setup-node@v5 + with: + node-version: 22 + + # Build the release wheel and test the installed wheel, not the source + # tree: what users install is what is tested. + - name: Build and install the wheel + run: | + python -m venv sdks/python/.venv + sdks/python/.venv/bin/pip install "maturin>=1.9.4,<2" pytest + sdks/python/.venv/bin/maturin build --release --manifest-path sdks/python/Cargo.toml --out dist-python + sdks/python/.venv/bin/pip install dist-python/*.whl + + # Unit tests, the shared evaluation vectors, the sync state machine + # against a local fake server, concurrency and fork safety. + - name: Tests + run: sdks/python/.venv/bin/python -m pytest sdks/python/tests -q + + # The shared SSE fault-injection suite (sdks/conformance), driving the + # Python client with the real Rust engine. + - name: SSE fault injection (CI seeds) + env: + PYTHON: ${{ github.workspace }}/sdks/python/.venv/bin/python + CONFORMANCE_TRACE_DIR: ${{ github.workspace }}/conformance-traces + run: node --test --test-concurrency=1 sdks/conformance/python.mjs + + - uses: actions/upload-artifact@v6 + if: failure() + with: + name: conformance-traces-python-${{ matrix.python }} + path: conformance-traces + retention-days: 30 + # --------------------------------------------------------------------------- # Go integrations — shared client, Terraform provider, Kubernetes operator # --------------------------------------------------------------------------- diff --git a/.github/workflows/python-wheels.yml b/.github/workflows/python-wheels.yml new file mode 100644 index 00000000..582051d7 --- /dev/null +++ b/.github/workflows/python-wheels.yml @@ -0,0 +1,71 @@ +name: Python wheels (native platforms) + +# Builds the Python SDK wheel ON each supported platform and runs the test +# suite against the installed wheel there — native testing, not +# cross-compilation. The release workflow builds the publishable wheels +# (manylinux, cross-built where needed) but only on a version tag; this is +# the evidence that each platform actually works before a release. +# Runs when the engine or the Python SDK changes, or by hand. + +on: + pull_request: + branches: [main, dev, "feat/**"] + paths: + - "core/**" + - "sdks/python/**" + - "sdks/conformance/vectors/**" + - ".github/workflows/python-wheels.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + native: + name: ${{ matrix.platform }} (Python ${{ matrix.python }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 40 + strategy: + fail-fast: false + matrix: + include: + - { platform: linux-x86_64, os: ubuntu-latest, python: "3.11" } + - { platform: linux-x86_64, os: ubuntu-latest, python: "3.13" } + - { platform: linux-aarch64, os: ubuntu-24.04-arm, python: "3.11" } + - { platform: macos-x86_64, os: macos-15-intel, python: "3.11" } + - { platform: macos-arm64, os: macos-latest, python: "3.11" } + - { platform: macos-arm64, os: macos-latest, python: "3.13" } + - { platform: windows-x86_64, os: windows-latest, python: "3.11" } + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python }} + + # The toolchain rust-toolchain.toml pins, as release.yml installs it: + # installing `stable` first and letting cargo fetch the pin conflicts on + # Windows runners (clippy's cargo-clippy.exe already present). + - name: Install Rust toolchain + run: rustup show + + - name: Build the wheel on this platform + run: | + python -m venv .venv-build + if [ -d .venv-build/Scripts ]; then BIN=.venv-build/Scripts; else BIN=.venv-build/bin; fi + "$BIN/pip" install "maturin>=1.9.4,<2" + "$BIN/maturin" build --release --manifest-path sdks/python/Cargo.toml --out dist-python + ls -l dist-python + + - name: Install the wheel in a clean environment and test it + run: | + python -m venv .venv-test + if [ -d .venv-test/Scripts ]; then BIN=.venv-test/Scripts; else BIN=.venv-test/bin; fi + "$BIN/pip" install pytest dist-python/*.whl + # Run from outside the source tree so the installed wheel is imported. + cd "$RUNNER_TEMP" + "$GITHUB_WORKSPACE/$BIN/python" -c "import checkgate, sys; print(checkgate.__file__, sys.version)" + "$GITHUB_WORKSPACE/$BIN/python" -m pytest "$GITHUB_WORKSPACE/sdks/python/tests" -q diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f1f276ab..bd3d9da5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -64,6 +64,29 @@ jobs: working-directory: ssr run: node --test + # Packages added in 0.2.0. Their tests run in CI (they need the native + # addon or a server); here: the MCP server's own tests, and that every + # package packs the files its manifest points at (an ignored bin/ + # once kept the MCP executable out of the repository). + - name: MCP server — tests + working-directory: integrations/mcp-server + run: npm ci --ignore-scripts && npm test + + - name: New packages — packaging integrity + run: | + set -euo pipefail + check() { + dir="$1"; shift + out="$(cd "$dir" && npm pack --dry-run --json 2>/dev/null)" + for f in "$@"; do + echo "$out" | grep -q "\"path\": \"$f\"" || { echo "Error: $dir does not pack $f"; exit 1; } + done + echo "$dir packs: $*" + } + check sdks/openfeature-provider src/index.js src/index.d.ts README.md + check sdks/node-integrations src/express.js src/fastify.js src/nestjs.js + check integrations/mcp-server bin/checkgate-mcp.js src/index.js README.md + - name: React Native — packaging integrity working-directory: sdks/react-native run: | @@ -271,6 +294,71 @@ jobs: working-directory: sdks/flutter/dart run: dart pub publish --dry-run + # Python wheels (sdks/python): abi3, one per platform for CPython 3.11+. + # VERIFY ONLY: the wheels are built (and, where the runner can run them, + # tested) and uploaded as workflow artifacts. There is no PyPI publish job + # yet, and this job is deliberately not in the publish jobs' `needs` until + # the Python SDK is released: a wheel failure must not block the npm, + # pub.dev and image releases before then. + build-python: + name: Verify — Python wheel ${{ matrix.platform }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + platform: linux-x86_64 + target: x86_64 + manylinux: auto + test: true + - os: ubuntu-latest + platform: linux-aarch64 + target: aarch64 + manylinux: auto + test: false # cross-built; not run on this runner + - os: macos-latest + platform: macos-x86_64 + target: x86_64 + test: false # cross-built on an arm64 runner + - os: macos-latest + platform: macos-arm64 + target: aarch64 + test: true + - os: windows-latest + platform: windows-x86_64 + target: x64 + test: true + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + + - name: Build wheel + uses: PyO3/maturin-action@v1 + with: + working-directory: sdks/python + target: ${{ matrix.target }} + manylinux: ${{ matrix.manylinux }} + args: --release --out dist + + - name: Test the installed wheel + if: matrix.test + shell: bash + run: | + python -m pip install pytest + python -m pip install --no-index --find-links sdks/python/dist checkgate + python -m pytest sdks/python/tests -q + + - name: Upload wheel + uses: actions/upload-artifact@v6 + with: + name: python-wheel-${{ matrix.platform }} + path: sdks/python/dist/*.whl + if-no-files-found: error + # Build the image without pushing, so a broken or vulnerable image blocks the # release instead of being discovered after the npm packages are already live. build-docker: @@ -514,6 +602,87 @@ jobs: env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + publish-openfeature: + name: Publish — @checkgate/openfeature-provider + needs: [verify-js, build-native, build-web, verify-flutter, build-docker] + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write # OIDC token for npm provenance + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 22 + registry-url: https://registry.npmjs.org + + - name: Set version from tag + working-directory: sdks/openfeature-provider + run: | + TAG="${{ github.ref_name }}" + VERSION="${TAG#v}" + npm version "$VERSION" --no-git-tag-version --allow-same-version + + - name: Publish @checkgate/openfeature-provider + working-directory: sdks/openfeature-provider + run: npm publish --access public --provenance + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + publish-node-integrations: + name: Publish — @checkgate/node-integrations + needs: [verify-js, build-native, build-web, verify-flutter, build-docker] + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write # OIDC token for npm provenance + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 22 + registry-url: https://registry.npmjs.org + + - name: Set version from tag + working-directory: sdks/node-integrations + run: | + TAG="${{ github.ref_name }}" + VERSION="${TAG#v}" + npm version "$VERSION" --no-git-tag-version --allow-same-version + + - name: Publish @checkgate/node-integrations + working-directory: sdks/node-integrations + run: npm publish --access public --provenance + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + publish-mcp-server: + name: Publish — @checkgate/mcp-server + needs: [verify-js, build-native, build-web, verify-flutter, build-docker] + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write # OIDC token for npm provenance + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 22 + registry-url: https://registry.npmjs.org + + - name: Set version from tag + working-directory: integrations/mcp-server + run: | + TAG="${{ github.ref_name }}" + VERSION="${TAG#v}" + npm version "$VERSION" --no-git-tag-version --allow-same-version + + - name: Publish @checkgate/mcp-server + working-directory: integrations/mcp-server + run: npm publish --access public --provenance + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + publish-react-native: name: Publish — @checkgate/react-native needs: [verify-js, build-native, build-web, verify-flutter, build-docker] @@ -650,6 +819,9 @@ jobs: - publish-cli - publish-edge - publish-ssr + - publish-openfeature + - publish-node-integrations + - publish-mcp-server - publish-react-native - publish-flutter - publish-docker diff --git a/.gitignore b/.gitignore index d18b4c5b..0dedeeab 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,9 @@ coverage/ .flutter-plugins-dependencies sdks/flutter/dart/build/ +# Compiled output of the NestJS integration example (npx tsc -p examples/nestjs). +sdks/node-integrations/examples/nestjs/dist/ + # TypeScript incremental build state — regenerated by every `tsc -b`, so # tracking it churns the diff on each commit. *.tsbuildinfo diff --git a/CHANGELOG.md b/CHANGELOG.md index 539b8a03..256b8d2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,78 @@ All notable changes to Checkgate are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/). +## [0.2.0] - Unreleased + +Developer adoption: OpenFeature, Python, framework integrations, a local +quickstart, an evaluation playground, SDK diagnostics and an MCP server for AI +agents. Every new SDK surface evaluates with the same Rust engine; no feature +adds a network request per evaluation. + +### Upgrading from 0.1.31 + +- **One database migration** (`20261121000029_pat_propose_scope`): it widens + the personal-access-token scope check to allow `propose`. It is additive and + applies on start. **A 0.1.31 binary will not start against a database that + has it** (the migrator reports an applied migration it does not know), so + there is no rolling mixed-version upgrade: replace all instances. +- **Create no `propose` tokens while any 0.1.31 instance is still serving**: + 0.1.31 does not know the scope and would let such a token create a + `read_write` token. +- **Rollback:** stop 0.2.0, delete every `propose` token, delete the + migration's row from `_sqlx_migrations`, start 0.1.31 (tested). Details: + docs/operations/upgrading-to-0-2-0.md. +- No configuration change is required. The SDK protocol (`/stream`, + `/flags/snapshot`) is unchanged, so 0.1.31 SDKs work with a 0.2.0 server and + 0.2.0 SDKs with a 0.1.31 server; the new server endpoints are additive. +- Building the Rust workspace now needs Python 3.11+ for the PyO3 crate + (`PYO3_PYTHON` selects the interpreter). + +### Added + +- **Core:** `explain()` — the same evaluation as `evaluate_variant`, plus the + reason (`DISABLED`, `PREREQUISITE_FAILED`, `TARGETING_MATCH`, + `ROLLOUT_EXCLUDED`, `SPLIT`, `DEFAULT`, `STATIC`), matched rule, rollout + bucket, weighted variant and prerequisite outcomes. Shared evaluation vectors + (`sdks/conformance/vectors/evaluation.json`) that every SDK checks. +- **Node.js SDK:** `getDetails()`, `onStatusChange()`, and `getHealth()` + (diagnostics schema 1, shared with Python). +- **`@checkgate/openfeature-provider`:** OpenFeature server-SDK provider over + `@checkgate/node`, with reason/variant mapping and READY/STALE/ERROR/FATAL + lifecycle. +- **Python SDK (`checkgate`):** PyO3 bindings to the engine; SSE, poll + fallback, revision ordering, offline cache, `get_details()`, `get_health()`; + FastAPI, Flask and Django examples. Runs the shared fault-injection suite. +- **`@checkgate/node-integrations`:** Express middleware, Fastify plugin and + NestJS module over one shared client, with request-scoped context and a + startup timeout policy. +- **Evaluation playground:** `POST /api/environments/{env}/flags/{key}/evaluate` + and a dashboard page — what an SDK would answer for a user, and why. Read-only. +- **SDK diagnostics on the server:** `last_delivered_revision` per stream, + `GET /api/health/environments` (convergence per environment), metrics + `checkgate_snapshot_requests_total` and `checkgate_playground_evaluations_total`. +- **`propose` personal access tokens:** read access plus proposing flag + changes (always a change request) and withdrawing their own requests; they + can never create a flag, apply, approve or reject. For automation and AI agents. +- **`@checkgate/mcp-server`:** stdio MCP server for AI agents — read-only by + default; with `CHECKGATE_MCP_WRITE=1`, change proposals through the normal + approval workflow (no tool creates, approves or applies anything). +- **Quickstart:** `quickstart/start.sh --seed` (local, development only) with + Node.js and Python examples; first-run snippets in the setup wizard and an + empty-environment checklist on the dashboard. + +### Changed + +- Node.js SDK: on a stream's `ready` the client now marks itself ready before + switching to `streaming`, so status listeners see `isReady()` on a first + connection. +- CI tests the Node.js SDK's native build, the OpenFeature provider and the + framework integrations on Node.js 22, 24 and 26 (Node.js 20 reached end of + life on 2026-04-30); the MCP server on 22. +- Packages not yet on a registry: the Python package (`checkgate` on PyPI) has + no publish job yet; `@checkgate/openfeature-provider`, + `@checkgate/node-integrations` and `@checkgate/mcp-server` publish with the + release (packaging checked in the release workflow). + ## [0.1.31] - 2026-11-21 ### Upgrading from 0.1.30 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6e81a851..452d9879 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,7 +5,9 @@ Thanks for your interest in contributing. This document covers how to get set up ## Prerequisites - Rust (the toolchain pinned in `rust-toolchain.toml`, installed automatically by rustup) -- Node.js 20+ (SDKs, CLI, docs; CI uses 22) +- Node.js 22+ (SDKs, CLI, docs; CI uses 22, 24 and 26) +- Python 3.11+ (the workspace includes the Python SDK's PyO3 crate, whose build script needs + an interpreter of at least 3.11; if `python3` is older, set `PYO3_PYTHON=/path/to/python3.11`) - Bun 1.4+ (dashboard) - Docker and Docker Compose (for integration tests) - `wasm-pack` (browser SDK) diff --git a/Cargo.lock b/Cargo.lock index a3c83311..a6298e79 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -372,6 +372,16 @@ dependencies = [ "serde_json", ] +[[package]] +name = "checkgate-python" +version = "0.1.31" +dependencies = [ + "checkgate-core", + "pyo3", + "serde", + "serde_json", +] + [[package]] name = "ciborium" version = "0.2.2" @@ -1949,6 +1959,63 @@ dependencies = [ "psl-types", ] +[[package]] +name = "pyo3" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229ca13b8a15bb0d1487b81ab975bfcd97513416499a8312011b6036e42e0de4" +dependencies = [ + "libc", + "once_cell", + "portable-atomic", + "pyo3-build-config", + "pyo3-ffi", + "pyo3-macros", +] + +[[package]] +name = "pyo3-build-config" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70130e2b6dd1ee589a8788026a429561ca5c40fa7a2fa7914c2282eddae24700" +dependencies = [ + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e7ff73c555c286d212d4ce7e5fbda845a973c4f61bd5f160f5f2c3c2a04d1c4" +dependencies = [ + "libc", + "pyo3-build-config", +] + +[[package]] +name = "pyo3-macros" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c46d2e5862c7bb8207e3b639f713dda3c499933444784154c11d013c5a691b60" +dependencies = [ + "proc-macro2", + "pyo3-macros-backend", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "pyo3-macros-backend" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b89f066f2ae72a2aef52d1537ca2fcd104440ebfadee06e97aa90738a25b9b" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "quanta" version = "0.12.6" @@ -2876,6 +2943,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "target-lexicon" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" + [[package]] name = "thiserror" version = "2.0.18" @@ -3495,7 +3568,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.48.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index fcc0ffaf..8181a9dc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ members = [ "sdks/web", "sdks/flutter/dart/rust", "sdks/react-native", + "sdks/python", ] resolver = "2" diff --git a/Dockerfile b/Dockerfile index 34a101f5..18008af4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -42,14 +42,18 @@ COPY sdks/nodejs/Cargo.toml sdks/nodejs/Cargo.toml COPY sdks/web/Cargo.toml sdks/web/Cargo.toml COPY sdks/flutter/dart/rust/Cargo.toml sdks/flutter/dart/rust/Cargo.toml COPY sdks/react-native/Cargo.toml sdks/react-native/Cargo.toml +# Every workspace member's manifest must be present for cargo to load the +# workspace, even though only the server is built here. +COPY sdks/python/Cargo.toml sdks/python/Cargo.toml -RUN mkdir -p core/src server/src sdks/nodejs/src sdks/web/src sdks/flutter/dart/rust/src sdks/react-native/src && \ +RUN mkdir -p core/src server/src sdks/nodejs/src sdks/web/src sdks/flutter/dart/rust/src sdks/react-native/src sdks/python/src && \ echo "fn main(){}" > server/src/main.rs && \ echo "" > core/src/lib.rs && \ echo "" > sdks/nodejs/src/lib.rs && \ echo "" > sdks/web/src/lib.rs && \ echo "" > sdks/flutter/dart/rust/src/lib.rs && \ - echo "" > sdks/react-native/src/lib.rs + echo "" > sdks/react-native/src/lib.rs && \ + echo "" > sdks/python/src/lib.rs RUN cargo build --release -p server 2>/dev/null || true diff --git a/README.md b/README.md index 2094e8e8..35408f7a 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,9 @@ The server and the shared evaluation core are written in Rust, with SDKs for Nod ## Quick start -Run the all-in-one image (PostgreSQL, Redis, the server and the dashboard in one container). Save as `compose.yml`: +From a clone, one script starts Checkgate locally, seeds a sample flag and prints an SDK key +(development only): `./quickstart/start.sh --seed` — see the +[five-minute quickstart](docs/guide/quickstart.md). Or, without a clone, run the all-in-one image (PostgreSQL, Redis, the server and the dashboard in one container). Save as `compose.yml`: ```yaml services: @@ -98,6 +100,15 @@ The full walkthrough (first flag, SDK keys, production settings): [Getting Start - **Observability** — Prometheus metrics, health and readiness endpoints - **Self-hosted** — single binary + PostgreSQL + Redis; no third-party service sees your flags or users +**New in 0.2.0** (unreleased; verified locally on macOS, CI pending — see each page for its tested platforms): + +- [OpenFeature provider](docs/sdks/openfeature.md) for Node.js — standard OpenFeature API, same local engine +- [Python SDK](docs/sdks/python.md) — PyO3 bindings to the same Rust engine; FastAPI, Django and Flask examples +- [Express, Fastify and NestJS integrations](docs/sdks/node-frameworks.md) — one shared client, per-request context +- [Evaluation playground](docs/guide/playground.md) — see what an SDK would answer for a user, and why +- [SDK diagnostics](docs/operations/sdk-diagnostics.md) — `getHealth()` in the Node.js and Python SDKs, convergence on the SDK Health page +- [MCP server for AI agents](docs/ecosystem/mcp.md) — read flags, propose changes through the normal approval flow (`propose` tokens cannot create, apply or approve) + **SDK status (v0.1.31):** Node.js and Web run unit, fault-injection and live end-to-end tests in CI. React Native's Android native build is verified in CI; its iOS build is not certified for this release. Flutter bundles no compiled engine yet: you build and link the Rust engine yourself ([how](docs/sdks/flutter.md#linking-the-native-engine)); verified on the iOS simulator. --- @@ -180,9 +191,13 @@ Method, assumptions and sources: [Infrastructure cost and efficiency](docs/perfo | System architecture | [Architecture](docs/guide/architecture.md) | | Flags, rules, rollout concepts | [Core Concepts](docs/guide/concepts.md) | | Dashboard tour | [Dashboard](docs/guide/dashboard.md) | +| Five-minute local quickstart | [Quickstart](docs/guide/quickstart.md) | | Step-by-step setup | [Getting Started](docs/guide/getting-started.md) | | REST API + SSE stream reference | [API Reference](docs/api-reference.md) | | Node.js SDK | [SDK: Node.js](docs/sdks/nodejs.md) | +| OpenFeature (Node.js) | [OpenFeature provider](docs/sdks/openfeature.md) | +| Python SDK | [SDK: Python](docs/sdks/python.md) | +| Express, Fastify, NestJS | [SDK: Node.js frameworks](docs/sdks/node-frameworks.md) | | Web (WASM) SDK | [SDK: Web](docs/sdks/web.md) | | React Native (JSI) SDK | [SDK: React Native](docs/sdks/react-native.md) | | Flutter (FFI) SDK | [SDK: Flutter](docs/sdks/flutter.md) | @@ -191,6 +206,7 @@ Method, assumptions and sources: [Infrastructure cost and efficiency](docs/perfo | SSR / bootstrap (Next.js, Remix, …) | [`@checkgate/ssr`](ssr/README.md) | | Terraform / OpenTofu provider | [terraform-provider-checkgate](integrations/terraform-provider-checkgate/README.md) | | Kubernetes operator | [checkgate-operator](integrations/kubernetes-operator/README.md) | +| AI agents (MCP) | [MCP server](docs/ecosystem/mcp.md) | | Docker, AWS, env vars | [Self-Hosting](docs/self-hosting.md) | | Enterprise Setup & Migration | [Enterprise Setup & Migration](docs/enterprise-setup.md) | diff --git a/bench/benches/evaluation.rs b/bench/benches/evaluation.rs index 39b4f987..d9eb6198 100644 --- a/bench/benches/evaluation.rs +++ b/bench/benches/evaluation.rs @@ -20,7 +20,7 @@ //! evaluation, retained bytes per stored flag) is printed as JSON lines, //! measured with a counting global allocator. -use checkgate_core::evaluator::{Flag, UserContext, evaluate, evaluate_variant}; +use checkgate_core::evaluator::{Flag, UserContext, evaluate, evaluate_variant, explain}; use checkgate_core::store::FlagStore; use criterion::{BenchmarkId, Criterion, Throughput, criterion_group}; use serde_json::json; @@ -284,6 +284,15 @@ fn rules(c: &mut Criterion) { g.bench_function("weighted_multivariate", |b| { b.iter(|| evaluate_variant(&store.get_flag(black_box("mv")).unwrap(), &ctx, &store)) }); + // The detailed path (OpenFeature details, the playground): same + // evaluator with a recorder, so its cost over the plain call is the + // price of the explanation alone. + g.bench_function("explain_targeting_10_rules", |b| { + b.iter(|| explain(&store.get_flag(black_box("t10")).unwrap(), &ctx, &store)) + }); + g.bench_function("explain_percentage_rollout", |b| { + b.iter(|| explain(&store.get_flag(black_box("rollout")).unwrap(), &ctx, &store)) + }); // Depth counts flags in the chain: 2 = a flag with one prerequisite. for depth in [2usize, 3, 5] { let s = store_with(1_000); diff --git a/core/src/evaluator.rs b/core/src/evaluator.rs index ac878aad..2530d96d 100644 --- a/core/src/evaluator.rs +++ b/core/src/evaluator.rs @@ -202,11 +202,28 @@ fn disabled_result(flag: &Flag) -> EvalResult { /// weights. Salted independently from the rollout-percentage hash (`:variant` suffix) /// so variant assignment doesn't correlate with which users pass the rollout gate. /// Zero total weight (all-zero or empty) falls back to the first variant. +#[cfg(test)] fn pick_weighted_variant( flag_key: &str, user_key: &str, variants: &[WeightedVariant], ) -> FlagValue { + weighted_variant_index(flag_key, user_key, variants) + .and_then(|i| variants.get(i)) + .map(|v| v.value.clone()) + .unwrap_or(FlagValue::Null) +} + +/// The index of the variant [`pick_weighted_variant`] returns, or `None` when +/// `variants` is empty. +fn weighted_variant_index( + flag_key: &str, + user_key: &str, + variants: &[WeightedVariant], +) -> Option { + if variants.is_empty() { + return None; + } let total: u64 = variants .iter() .map(|v| u64::from(v.weight)) @@ -216,10 +233,7 @@ fn pick_weighted_variant( // type-level guarantee: `u64 % NonZeroU64` cannot divide by zero, so the // remainder below has no panic path at all. let Some(total_weight) = NonZeroU64::new(total) else { - return variants - .first() - .map(|v| v.value.clone()) - .unwrap_or(FlagValue::Null); + return Some(0); }; // Hashes the bytes of `"{flag_key}:{user_key}:variant"` without building @@ -237,17 +251,21 @@ fn pick_weighted_variant( }; let mut cumulative = 0u64; - for variant in variants { + for (index, variant) in variants.iter().enumerate() { cumulative = cumulative.saturating_add(u64::from(variant.weight)); if bucket < cumulative { - return variant.value.clone(); + return Some(index); } } // Unreachable given bucket < total_weight == final cumulative, but guard anyway. - variants - .last() - .map(|v| v.value.clone()) - .unwrap_or(FlagValue::Null) + Some(variants.len().saturating_sub(1)) +} + +/// The user's rollout bucket for `flag`, in `0..100`. A user is inside a +/// rollout of `p` percent when their bucket is below `p`. +fn rollout_bucket(flag_key: &str, user_key: &str) -> u32 { + // Hashes the bytes of `"{flag_key}:{user_key}"` without building that string. + murmurhash3_x86_32_concat(&[flag_key.as_bytes(), b":", user_key.as_bytes()], 0) % 100 } /// Prerequisite chains deeper than this are treated as unsatisfied (fail closed). @@ -268,33 +286,208 @@ const MAX_PREREQUISITE_DEPTH: usize = 10; /// saved before that check, or written by other means. const MAX_PREREQUISITE_EVALUATIONS: u32 = 1_000; +/// Why an evaluation resolved the way it did. The vocabulary follows the +/// [OpenFeature resolution reasons](https://openfeature.dev/specification/types#resolution-reason), +/// plus the two outcomes OpenFeature has no standard word for. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +#[non_exhaustive] +pub enum Reason { + /// The flag is switched off (`is_enabled: false`). + Disabled, + /// A prerequisite was not satisfied, so the flag resolved as disabled. + PrerequisiteFailed, + /// A targeting rule matched (see [`Explanation::rule_index`]). + TargetingMatch, + /// The user's rollout bucket is outside the rollout percentage, so the + /// flag resolved as disabled (see [`Explanation::rollout_bucket`]). + RolloutExcluded, + /// The outcome was decided by hashing the user key: the user passed a + /// partial rollout, or was assigned a weighted variant. + Split, + /// The flag has targeting rules, none matched, and the user got the + /// flag's default value. + Default, + /// The flag has no rules, partial rollout or variants: every user gets + /// the same value. + Static, +} + +/// How one prerequisite of the explained flag was judged. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum PrerequisiteOutcome { + /// The prerequisite flag resolved as required. + Satisfied, + /// The prerequisite flag resolved, but not as required. + Unsatisfied, + /// No flag with that key exists (fails closed). + NotFound, + /// The depth or evaluation limit was reached before it could be + /// evaluated (fails closed). + LimitExceeded, +} + +/// One prerequisite of the explained flag, in the order they were checked. +/// Checking stops at the first prerequisite that is not satisfied, so later +/// ones are absent. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[non_exhaustive] +pub struct PrerequisiteCheck { + pub flag_key: String, + pub outcome: PrerequisiteOutcome, + /// The value the prerequisite must resolve to; `None` means "enabled". + #[serde(default, skip_serializing_if = "Option::is_none")] + pub required_value: Option, + /// What the prerequisite resolved to; `None` when it was not evaluated. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub result: Option, +} + +/// An evaluation together with the path that produced it: the same result +/// [`evaluate_variant`] returns, from the same code, plus why. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[non_exhaustive] +pub struct Explanation { + pub enabled: bool, + pub value: FlagValue, + pub reason: Reason, + /// Index into `Flag::rules` of the rule that matched. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rule_index: Option, + /// The user's rollout bucket (`0..100`) when a partial rollout + /// (`0 < rollout_percentage < 100`) was checked. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rollout_bucket: Option, + /// Index into `Flag::variants` of the weighted variant assigned. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub variant_index: Option, + /// The flag's own prerequisites as they were checked (not those of + /// prerequisites further down the chain). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub prerequisites: Vec, +} + +impl Explanation { + /// The plain result, as [`evaluate_variant`] returns it. + #[must_use] + pub fn result(&self) -> EvalResult { + EvalResult { + enabled: self.enabled, + value: self.value.clone(), + } + } +} + +/// Observes the decisions one evaluation makes. [`evaluate_variant`] runs with +/// [`NoTrace`], whose empty methods compile away, so the hot path is the same +/// machine code it was before explanations existed; [`explain`] runs the very +/// same function with a recorder. One evaluator, two views of it. +trait Trace { + fn reason(&mut self, _reason: Reason) {} + fn rule(&mut self, _index: usize) {} + fn rollout_bucket(&mut self, _bucket: u32) {} + fn variant(&mut self, _index: usize) {} + /// Only called for the top-level flag's own prerequisites. + fn prerequisite(&mut self, _check: PrerequisiteCheck) {} + /// Whether [`Trace::prerequisite`] does anything; lets the caller skip + /// building the check (it clones values) when nobody records it. + fn records_prerequisites(&self) -> bool { + false + } +} + +struct NoTrace; +impl Trace for NoTrace {} + +#[derive(Default)] +struct Recorder { + reason: Option, + rule_index: Option, + rollout_bucket: Option, + variant_index: Option, + prerequisites: Vec, +} + +impl Trace for Recorder { + fn reason(&mut self, reason: Reason) { + self.reason = Some(reason); + } + fn rule(&mut self, index: usize) { + self.rule_index = Some(index); + } + fn rollout_bucket(&mut self, bucket: u32) { + self.rollout_bucket = Some(bucket); + } + fn variant(&mut self, index: usize) { + self.variant_index = Some(index); + } + fn prerequisite(&mut self, check: PrerequisiteCheck) { + self.prerequisites.push(check); + } + fn records_prerequisites(&self) -> bool { + true + } +} + /// Evaluate a flag and return both the on/off result and the resolved variant value. /// Use this for non-boolean flags (string / integer / JSON variants). `store` is /// used to resolve the flag's prerequisites (if any) — pass the same store the /// flag itself was looked up from. pub fn evaluate_variant(flag: &Flag, user_context: &UserContext, store: &FlagStore) -> EvalResult { let mut budget = MAX_PREREQUISITE_EVALUATIONS; - evaluate_variant_at_depth(flag, user_context, store, 0, &mut budget) + evaluate_variant_at_depth(flag, user_context, store, 0, &mut budget, &mut NoTrace) +} + +/// Evaluate a flag and report why it resolved as it did: the reason, the +/// matched rule, the rollout bucket, the weighted variant and the outcome of +/// each prerequisite. The result is the one [`evaluate_variant`] returns for +/// the same inputs, computed by the same code. Costs more than +/// `evaluate_variant` (it records the path), so use it for debugging and +/// detailed SDK APIs, not as the default evaluation. +#[must_use] +pub fn explain(flag: &Flag, user_context: &UserContext, store: &FlagStore) -> Explanation { + let mut budget = MAX_PREREQUISITE_EVALUATIONS; + let mut recorder = Recorder::default(); + let result = + evaluate_variant_at_depth(flag, user_context, store, 0, &mut budget, &mut recorder); + Explanation { + enabled: result.enabled, + value: result.value, + // Every return path of the evaluator reports a reason; `Disabled` is + // the fail-closed answer should one ever be added without it. + reason: recorder.reason.unwrap_or(Reason::Disabled), + rule_index: recorder.rule_index, + rollout_bucket: recorder.rollout_bucket, + variant_index: recorder.variant_index, + prerequisites: recorder.prerequisites, + } } -fn evaluate_variant_at_depth( +fn evaluate_variant_at_depth( flag: &Flag, user_context: &UserContext, store: &FlagStore, depth: usize, budget: &mut u32, + trace: &mut T, ) -> EvalResult { if !flag.is_enabled { + trace.reason(Reason::Disabled); return disabled_result(flag); } - if !prerequisites_satisfied(flag, user_context, store, depth, budget) { + if !prerequisites_satisfied(flag, user_context, store, depth, budget, trace) { + trace.reason(Reason::PrerequisiteFailed); return disabled_result(flag); } // Targeting rules — first match wins; per-rule variant overrides the flag default. - for rule in &flag.rules { + for (index, rule) in flag.rules.iter().enumerate() { if rule_matches(rule, user_context) { + trace.reason(Reason::TargetingMatch); + trace.rule(index); let value = rule .variant .clone() @@ -308,30 +501,43 @@ fn evaluate_variant_at_depth( } // Rollout bucket check + let mut hashed = false; if let Some(percentage) = flag.rollout_percentage { if percentage == 0 { + trace.reason(Reason::RolloutExcluded); return disabled_result(flag); } if percentage < 100 { - // Hashes the bytes of `"{flag.key}:{user_context.key}"` without - // building that string. - let hash_val = murmurhash3_x86_32_concat( - &[flag.key.as_bytes(), b":", user_context.key.as_bytes()], - 0, - ); - if hash_val % 100 >= percentage { + let bucket = rollout_bucket(&flag.key, &user_context.key); + trace.rollout_bucket(bucket); + if bucket >= percentage { + trace.reason(Reason::RolloutExcluded); return disabled_result(flag); } + hashed = true; } } - let value = if !flag.variants.is_empty() { - pick_weighted_variant(&flag.key, &user_context.key, &flag.variants) + let value = + if let Some(index) = weighted_variant_index(&flag.key, &user_context.key, &flag.variants) { + trace.variant(index); + hashed = true; + flag.variants + .get(index) + .map(|v| v.value.clone()) + .unwrap_or(FlagValue::Null) + } else { + flag.default_value + .clone() + .unwrap_or_else(|| enabled_default(flag)) + }; + trace.reason(if hashed { + Reason::Split + } else if flag.rules.is_empty() { + Reason::Static } else { - flag.default_value - .clone() - .unwrap_or_else(|| enabled_default(flag)) - }; + Reason::Default + }); EvalResult { enabled: true, @@ -345,26 +551,49 @@ fn evaluate_variant_at_depth( /// cycles, e.g. A requires B, B requires A), or a prerequisite reached after the /// evaluation's `MAX_PREREQUISITE_EVALUATIONS` budget is spent, is treated as /// unsatisfied. Stops at the first unsatisfied prerequisite. -fn prerequisites_satisfied( +/// +/// `trace` sees only this flag's own prerequisites; flags further down the +/// chain are evaluated untraced. +fn prerequisites_satisfied( flag: &Flag, user_context: &UserContext, store: &FlagStore, depth: usize, budget: &mut u32, + trace: &mut T, ) -> bool { if flag.prerequisites.is_empty() { return true; } + let record = trace.records_prerequisites(); + let report = |trace: &mut T, + prereq: &Prerequisite, + outcome: PrerequisiteOutcome, + result: Option<&EvalResult>| { + if record { + trace.prerequisite(PrerequisiteCheck { + flag_key: prereq.flag_key.clone(), + outcome, + required_value: prereq.required_value.clone(), + result: result.cloned(), + }); + } + }; if depth >= MAX_PREREQUISITE_DEPTH { + if let Some(first) = flag.prerequisites.first() { + report(trace, first, PrerequisiteOutcome::LimitExceeded, None); + } return false; } for prereq in &flag.prerequisites { let Some(remaining) = budget.checked_sub(1) else { + report(trace, prereq, PrerequisiteOutcome::LimitExceeded, None); return false; }; *budget = remaining; let Some(prereq_flag) = store.get_flag(&prereq.flag_key) else { + report(trace, prereq, PrerequisiteOutcome::NotFound, None); return false; }; let result = evaluate_variant_at_depth( @@ -373,11 +602,18 @@ fn prerequisites_satisfied( store, depth.saturating_add(1), budget, + &mut NoTrace, ); let satisfied = match &prereq.required_value { Some(required) => result.enabled && &result.value == required, None => result.enabled, }; + let outcome = if satisfied { + PrerequisiteOutcome::Satisfied + } else { + PrerequisiteOutcome::Unsatisfied + }; + report(trace, prereq, outcome, Some(&result)); if !satisfied { return false; } @@ -1560,4 +1796,280 @@ mod tests { FlagValue::Json(json) ); } + + // ----------------------------------------------------------------- + // explain(): same result as evaluate_variant, plus the path taken + // ----------------------------------------------------------------- + + fn ctx(key: &str, attrs: &[(&str, &str)]) -> UserContext { + UserContext { + key: key.into(), + attributes: attrs + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(), + } + } + + fn rule(attribute: &str, operator: Operator, values: &[&str]) -> TargetingRule { + TargetingRule { + attribute: attribute.into(), + operator, + values: values.iter().map(|v| (*v).to_owned()).collect(), + segment_key: None, + variant: None, + } + } + + #[test] + fn explain_reports_matched_rule_index() { + let flag = bool_flag( + "f", + true, + Some(0), + vec![ + rule("plan", Operator::Equals, &["pro"]), + rule("country", Operator::Equals, &["PH"]), + ], + ); + let e = explain(&flag, &ctx("u", &[("country", "PH")]), &FlagStore::new()); + assert_eq!(e.reason, Reason::TargetingMatch); + assert_eq!(e.rule_index, Some(1)); + assert!(e.enabled); + let e = explain(&flag, &ctx("u", &[]), &FlagStore::new()); + assert_eq!(e.reason, Reason::RolloutExcluded); + assert_eq!(e.rule_index, None); + assert_eq!(e.rollout_bucket, None, "0% is decided without hashing"); + } + + #[test] + fn explain_reports_rollout_bucket_consistently_with_the_gate() { + let flag = bool_flag("gate", true, Some(40), vec![]); + for i in 0..500 { + let e = explain(&flag, &ctx(&format!("user{i}"), &[]), &FlagStore::new()); + let bucket = e.rollout_bucket.expect("partial rollout is hashed"); + assert!(bucket < 100); + assert_eq!(e.enabled, bucket < 40); + assert_eq!( + e.reason, + if e.enabled { + Reason::Split + } else { + Reason::RolloutExcluded + } + ); + } + } + + #[test] + fn explain_reports_static_default_and_variant() { + let store = FlagStore::new(); + let plain = bool_flag("plain", true, None, vec![]); + assert_eq!( + explain(&plain, &ctx("u", &[]), &store).reason, + Reason::Static + ); + let full = bool_flag("full", true, Some(100), vec![]); + assert_eq!( + explain(&full, &ctx("u", &[]), &store).reason, + Reason::Static + ); + let ruled = bool_flag( + "ruled", + true, + None, + vec![rule("a", Operator::Equals, &["b"])], + ); + assert_eq!( + explain(&ruled, &ctx("u", &[]), &store).reason, + Reason::Default + ); + + let mut weighted = bool_flag("w", true, None, vec![]); + weighted.flag_type = FlagType::String; + weighted.variants = vec![ + WeightedVariant { + weight: 1, + value: FlagValue::Str("x".into()), + }, + WeightedVariant { + weight: 1, + value: FlagValue::Str("y".into()), + }, + ]; + let e = explain(&weighted, &ctx("u", &[]), &store); + assert_eq!(e.reason, Reason::Split); + let index = e.variant_index.unwrap(); + assert_eq!(e.value, weighted.variants[index].value); + } + + #[test] + fn explain_reports_prerequisites_and_stops_at_the_first_failure() { + let store = FlagStore::new(); + store.upsert_flag(bool_flag("on", true, None, vec![])); + store.upsert_flag(bool_flag("off", false, None, vec![])); + let mut flag = bool_flag("child", true, None, vec![]); + flag.prerequisites = vec![ + Prerequisite { + flag_key: "on".into(), + required_value: None, + }, + Prerequisite { + flag_key: "off".into(), + required_value: None, + }, + Prerequisite { + flag_key: "never-checked".into(), + required_value: None, + }, + ]; + let e = explain(&flag, &ctx("u", &[]), &store); + assert_eq!(e.reason, Reason::PrerequisiteFailed); + assert!(!e.enabled); + let outcomes: Vec<_> = e + .prerequisites + .iter() + .map(|p| (p.flag_key.as_str(), p.outcome)) + .collect(); + assert_eq!( + outcomes, + vec![ + ("on", PrerequisiteOutcome::Satisfied), + ("off", PrerequisiteOutcome::Unsatisfied) + ] + ); + assert_eq!( + e.prerequisites[1].result, + Some(EvalResult { + enabled: false, + value: FlagValue::Bool(false) + }) + ); + + flag.prerequisites = vec![Prerequisite { + flag_key: "ghost".into(), + required_value: None, + }]; + let e = explain(&flag, &ctx("u", &[]), &store); + assert_eq!(e.prerequisites[0].outcome, PrerequisiteOutcome::NotFound); + assert_eq!(e.prerequisites[0].result, None); + } + + #[test] + fn explain_reports_a_cycle_as_a_failed_prerequisite() { + let store = FlagStore::new(); + let mut a = bool_flag("a", true, None, vec![]); + a.prerequisites = vec![Prerequisite { + flag_key: "b".into(), + required_value: None, + }]; + let mut b = bool_flag("b", true, None, vec![]); + b.prerequisites = vec![Prerequisite { + flag_key: "a".into(), + required_value: None, + }]; + store.upsert_flag(a.clone()); + store.upsert_flag(b); + let e = explain(&a, &ctx("u", &[]), &store); + assert_eq!(e.reason, Reason::PrerequisiteFailed); + // The direct prerequisite was evaluated (and failed further down). + assert_eq!(e.prerequisites[0].outcome, PrerequisiteOutcome::Unsatisfied); + } + + #[test] + fn explanation_serializes_with_the_documented_wire_names() { + let flag = bool_flag("f", true, Some(50), vec![]); + let e = explain(&flag, &ctx("u", &[]), &FlagStore::new()); + let v = serde_json::to_value(&e).unwrap(); + assert!(v["reason"] == "SPLIT" || v["reason"] == "ROLLOUT_EXCLUDED"); + assert!(v["rollout_bucket"].is_u64()); + assert!(v.get("rule_index").is_none(), "absent fields are omitted"); + assert!(v.get("prerequisites").is_none()); + } + + /// A deterministic stream of pseudo-random numbers (no new dependency). + struct Lcg(u64); + impl Lcg { + fn next(&mut self, bound: u64) -> u64 { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + (self.0 >> 33) % bound + } + } + + #[test] + fn explain_agrees_with_evaluate_variant_on_random_configurations() { + let ops = [ + Operator::Equals, + Operator::NotEquals, + Operator::Contains, + Operator::StartsWith, + Operator::EndsWith, + Operator::GreaterThan, + Operator::GreaterThanOrEqual, + Operator::LessThan, + Operator::LessThanOrEqual, + ]; + let words = ["1", "5", "10", "pro", "free", "ph", "x"]; + let mut rng = Lcg(0x5eed); + for round in 0..300 { + let store = FlagStore::new(); + let count = 6; + for i in 0..count { + let mut f = bool_flag(&format!("f{i}"), rng.next(5) != 0, None, vec![]); + f.rollout_percentage = match rng.next(4) { + 0 => None, + 1 => Some(0), + 2 => Some(100), + _ => Some(u32::try_from(rng.next(100)).unwrap()), + }; + for _ in 0..rng.next(3) { + let mut r = rule( + ["a", "b", "c"][usize::try_from(rng.next(3)).unwrap()], + ops[usize::try_from(rng.next(9)).unwrap()].clone(), + &[words[usize::try_from(rng.next(7)).unwrap()]], + ); + if rng.next(2) == 0 { + r.variant = Some(FlagValue::Str("rule".into())); + } + f.rules.push(r); + } + if rng.next(3) == 0 { + f.flag_type = FlagType::String; + f.variants = (0..rng.next(4)) + .map(|w| WeightedVariant { + weight: u32::try_from(rng.next(5)).unwrap(), + value: FlagValue::Str(format!("v{w}")), + }) + .collect(); + } + for _ in 0..rng.next(3) { + f.prerequisites.push(Prerequisite { + flag_key: format!("f{}", rng.next(count + 1)), + required_value: None, + }); + } + store.upsert_flag(f); + } + for u in 0..20 { + let c = ctx( + &format!("r{round}u{u}"), + &[ + ("a", words[usize::try_from(rng.next(7)).unwrap()]), + ("b", words[usize::try_from(rng.next(7)).unwrap()]), + ], + ); + for f in store.list_flags() { + let e = explain(&f, &c, &store); + assert_eq!(e.result(), evaluate_variant(&f, &c, &store)); + assert_eq!(e.rule_index.is_some(), e.reason == Reason::TargetingMatch); + if let Some(i) = e.rule_index { + assert!(rule_matches(&f.rules[i], &c)); + } + } + } + } + } } diff --git a/core/src/store.rs b/core/src/store.rs index e5f35e45..91cfba1f 100644 --- a/core/src/store.rs +++ b/core/src/store.rs @@ -37,6 +37,32 @@ impl FlagStore { pub fn clear(&self) { self.flags.clear(); } + + /// A new store holding the same flags, independent of this one: changes + /// to either are not seen by the other. The flags themselves are shared + /// (`Arc` clones), so this copies one pointer per flag, never flag data. + /// + /// Lets a binding build the next version of its flag set beside the one + /// being evaluated and swap it in whole (copy-on-write), so a concurrent + /// evaluation sees either the old set or the new one, never a mix. + #[must_use] + pub fn independent_copy(&self) -> Self { + Self { + flags: Arc::new((*self.flags).clone()), + } + } + + /// Number of flags held. + #[must_use] + pub fn len(&self) -> usize { + self.flags.len() + } + + /// Whether the store holds no flags. + #[must_use] + pub fn is_empty(&self) -> bool { + self.flags.is_empty() + } } #[cfg(test)] @@ -136,6 +162,28 @@ mod tests { ); } + #[test] + fn independent_copy_shares_flags_but_not_changes() { + let store = FlagStore::new(); + store.upsert_flag(mk("a", true)); + let copy = store.independent_copy(); + assert_eq!(copy.len(), 1); + assert!(Arc::ptr_eq( + &store.get_flag("a").unwrap(), + ©.get_flag("a").unwrap() + )); + copy.upsert_flag(mk("b", true)); + copy.delete_flag("a"); + assert!(store.get_flag("a").is_some(), "original keeps its flag"); + assert!( + store.get_flag("b").is_none(), + "original never sees the copy's write" + ); + assert_eq!(store.len(), 1); + assert!(!store.is_empty()); + assert!(FlagStore::new().is_empty()); + } + #[test] fn get_flag_returns_cheap_arc_clone() { let store = FlagStore::new(); diff --git a/core/tests/vectors.rs b/core/tests/vectors.rs new file mode 100644 index 00000000..a08039fd --- /dev/null +++ b/core/tests/vectors.rs @@ -0,0 +1,158 @@ +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::indexing_slicing, + clippy::arithmetic_side_effects, + reason = "test code: a panic here is an assertion failure, not a DoS" +)] +//! The shared evaluation vectors (`sdks/conformance/vectors/evaluation.json`). +//! +//! The Rust core is the oracle: this test checks that the file's `expect` +//! entries are what the core computes, and every SDK checks itself against +//! the same file. After a deliberate semantic change, regenerate with +//! `CHECKGATE_BLESS_VECTORS=1 cargo test -p checkgate-core --test vectors` +//! and review the diff: every changed line is a behaviour change users see. + +use checkgate_core::evaluator::{evaluate_variant, explain, Flag, UserContext}; +use checkgate_core::store::FlagStore; +use serde_json::{json, Value}; +use std::path::PathBuf; + +fn vectors_path() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../sdks/conformance/vectors/evaluation.json") +} + +fn store(doc: &Value) -> FlagStore { + let store = FlagStore::new(); + for flag in doc["flags"].as_array().unwrap() { + let parsed: Flag = serde_json::from_value(flag.clone()) + .unwrap_or_else(|e| panic!("vector flag {} must parse: {e}", flag["key"])); + store.upsert_flag(parsed); + } + store +} + +fn context(case: &Value) -> UserContext { + UserContext { + key: case["user"].as_str().unwrap().to_owned(), + attributes: case["attributes"] + .as_object() + .unwrap() + .iter() + .map(|(k, v)| { + ( + k.clone(), + v.as_str() + .expect("vector attributes are strings") + .to_owned(), + ) + }) + .collect(), + } +} + +/// What every SDK must reproduce for one case, or `null` for a missing flag. +fn expected(store: &FlagStore, case: &Value) -> Value { + let Some(flag) = store.get_flag(case["flag"].as_str().unwrap()) else { + return Value::Null; + }; + let ctx = context(case); + let explanation = explain(&flag, &ctx, store); + // The explanation must be the plain evaluation, plus why. + assert_eq!( + explanation.result(), + evaluate_variant(&flag, &ctx, store), + "explain and evaluate_variant disagree on {}", + case["name"] + ); + let mut out = json!({ + "enabled": explanation.enabled, + "value": explanation.value, + "reason": explanation.reason, + }); + let obj = out.as_object_mut().unwrap(); + if let Some(i) = explanation.rule_index { + obj.insert("rule_index".into(), json!(i)); + } + if let Some(b) = explanation.rollout_bucket { + obj.insert("rollout_bucket".into(), json!(b)); + } + if let Some(i) = explanation.variant_index { + obj.insert("variant_index".into(), json!(i)); + } + out +} + +#[test] +fn vectors_match_the_core() { + let raw = std::fs::read_to_string(vectors_path()).expect("vectors file"); + let mut doc: Value = serde_json::from_str(&raw).expect("vectors are JSON"); + let store = store(&doc); + let bless = std::env::var_os("CHECKGATE_BLESS_VECTORS").is_some(); + + let mut mismatches = Vec::new(); + let mut names = std::collections::HashSet::new(); + for case in doc["cases"].as_array_mut().unwrap() { + assert!( + names.insert(case["name"].as_str().unwrap().to_owned()), + "duplicate case name {}", + case["name"] + ); + let want = expected(&store, case); + if bless { + case["expect"] = want; + } else if case.get("expect") != Some(&want) { + mismatches.push(format!( + "{}: file says {}, core computes {want}", + case["name"], + case.get("expect").unwrap_or(&Value::Null) + )); + } + } + + for bad in doc["malformed"].as_array().unwrap() { + let json = bad["json"].as_str().unwrap(); + assert!( + serde_json::from_str::(json).is_err(), + "malformed vector must be rejected: {json}" + ); + } + + if bless { + let mut text = serde_json::to_string_pretty(&doc).unwrap(); + text.push('\n'); + std::fs::write(vectors_path(), text).unwrap(); + return; + } + assert!( + mismatches.is_empty(), + "{} vector(s) disagree with the core (bless after a deliberate change):\n{}", + mismatches.len(), + mismatches.join("\n") + ); +} + +#[test] +fn every_reason_is_covered() { + // A new reason without a vector would let SDKs drift on it unnoticed. + let raw = std::fs::read_to_string(vectors_path()).unwrap(); + let doc: Value = serde_json::from_str(&raw).unwrap(); + let seen: std::collections::HashSet<&str> = doc["cases"] + .as_array() + .unwrap() + .iter() + .filter_map(|c| c["expect"]["reason"].as_str()) + .collect(); + for reason in [ + "DISABLED", + "PREREQUISITE_FAILED", + "TARGETING_MATCH", + "ROLLOUT_EXCLUDED", + "SPLIT", + "DEFAULT", + "STATIC", + ] { + assert!(seen.contains(reason), "no vector produces {reason}"); + } +} diff --git a/dashboard/src/App.tsx b/dashboard/src/App.tsx index b2454ee1..139a8212 100644 --- a/dashboard/src/App.tsx +++ b/dashboard/src/App.tsx @@ -6,6 +6,7 @@ import Layout from './components/Layout' import Login from './pages/Login' import Setup from './pages/Setup' import AuditLog from './pages/AuditLog' +import Playground from './pages/Playground' import Dashboard from './pages/Dashboard' import FlagList from './pages/FlagList' import Scheduled from './pages/Scheduled' @@ -106,6 +107,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/dashboard/src/api.ts b/dashboard/src/api.ts index 05ef23fe..8891eaff 100644 --- a/dashboard/src/api.ts +++ b/dashboard/src/api.ts @@ -1,6 +1,7 @@ import type { AuditEntry, ConnectedClient, + EnvironmentHealth, EventKeyInfo, Experiment, ExperimentResults, @@ -14,6 +15,7 @@ import type { IntegrationDelivery, IntegrationKind, IntegrationTestResult, + PlaygroundEvaluation, ScheduledChange, Segment, SegmentPatch, @@ -98,6 +100,23 @@ export const api = { return request(`/api/environments/${envId}/flags/${encodeURIComponent(key)}`) }, + /** + * Evaluates a flag for a hypothetical user on the server, with the SDK + * engine and the configuration revision SDKs are served. Changes nothing + * and stores nothing. + */ + evaluateFlag( + envId: string, + key: string, + targetingKey: string, + attributes: Record, + ): Promise { + return request(`/api/environments/${envId}/flags/${encodeURIComponent(key)}/evaluate`, { + method: 'POST', + body: JSON.stringify({ targeting_key: targetingKey, attributes }), + }) + }, + createFlag(envId: string, flag: Flag): Promise { return request(`/api/environments/${envId}/flags`, { method: 'POST', @@ -352,6 +371,9 @@ export const healthApi = { connections(): Promise { return request('/api/health/connections') }, + environments(): Promise { + return request('/api/health/environments') + }, } export const userApi = { @@ -407,7 +429,12 @@ export const keysApi = { }, } -export type TokenScope = 'read_only' | 'read_write' +/** + * `propose` (for AI agents and other automation): reads, plus proposing flag + * changes that someone else must approve — it can never apply, approve or + * reject a change itself. + */ +export type TokenScope = 'read_only' | 'propose' | 'read_write' export interface TokenInfo { id: number diff --git a/dashboard/src/components/QuickstartSnippets.test.tsx b/dashboard/src/components/QuickstartSnippets.test.tsx new file mode 100644 index 00000000..16cb46ff --- /dev/null +++ b/dashboard/src/components/QuickstartSnippets.test.tsx @@ -0,0 +1,28 @@ +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { describe, it, expect } from 'vitest' +import QuickstartSnippets, { quickstartSnippet } from './QuickstartSnippets' + +describe('quickstartSnippet', () => { + it('embeds the key only when given one; otherwise reads it from the environment', () => { + const withKey = quickstartSnippet('node', 'http://localhost:3000', 'new-checkout', 'sk_live_abc') + expect(withKey).toContain("sdkKey: 'sk_live_abc'") + const without = quickstartSnippet('node', 'http://localhost:3000', 'new-checkout') + expect(without).toContain('process.env.CHECKGATE_SDK_KEY') + expect(without).not.toContain('sk_') + const py = quickstartSnippet('python', 'http://localhost:3000', 'new-checkout') + expect(py).toContain('os.environ["CHECKGATE_SDK_KEY"]') + expect(py).toContain('client.is_enabled("new-checkout", "user-123", {"plan": "pro"})') + expect(quickstartSnippet('python', 'http://x', 'f', 'sk_1')).toContain('CheckgateClient("http://x", "sk_1")') + }) +}) + +describe('QuickstartSnippets', () => { + it('switches between Node.js and Python', async () => { + const user = userEvent.setup() + render() + expect(screen.getByTestId('quickstart-snippets')).toHaveTextContent('@checkgate/node') + await user.click(screen.getByRole('tab', { name: 'Python' })) + expect(screen.getByTestId('quickstart-snippets')).toHaveTextContent('pip install checkgate') + }) +}) diff --git a/dashboard/src/components/QuickstartSnippets.tsx b/dashboard/src/components/QuickstartSnippets.tsx new file mode 100644 index 00000000..aff62494 --- /dev/null +++ b/dashboard/src/components/QuickstartSnippets.tsx @@ -0,0 +1,85 @@ +import { useState } from 'react' +import { Check, Copy } from 'lucide-react' + +// Copyable "install and evaluate" snippets for the first-run experience. +// With `sdkKey` the snippet is ready to paste (shown once, right after setup); +// without it the key is read from CHECKGATE_SDK_KEY, so a key never lands in +// a snippet someone might paste into a repository. + +type Lang = 'node' | 'python' + +export function quickstartSnippet(lang: Lang, serverUrl: string, flagKey: string, sdkKey?: string): string { + const key = sdkKey ? `'${sdkKey}'` : null + if (lang === 'python') { + return [ + '# pip install checkgate (not on PyPI yet: build sdks/python from the repository)', + 'import os', + 'from checkgate import CheckgateClient', + '', + `client = CheckgateClient("${serverUrl}", ${key ? key.replace(/'/g, '"') : 'os.environ["CHECKGATE_SDK_KEY"]'})`, + 'client.connect(timeout=10)', + `print(client.is_enabled("${flagKey}", "user-123", {"plan": "pro"}))`, + 'client.close()', + ].join('\n') + } + return [ + '// npm install @checkgate/node', + "const { CheckgateClient } = require('@checkgate/node')", + '', + `const client = new CheckgateClient({ serverUrl: '${serverUrl}', sdkKey: ${key ?? 'process.env.CHECKGATE_SDK_KEY'} })`, + 'client.connect().then(() => {', + ` console.log(client.isEnabled('${flagKey}', 'user-123', { plan: 'pro' }))`, + ' client.disconnect()', + '})', + ].join('\n') +} + +export default function QuickstartSnippets({ sdkKey, flagKey = 'new-checkout' }: { sdkKey?: string; flagKey?: string }) { + const [lang, setLang] = useState('node') + const [copied, setCopied] = useState(false) + const serverUrl = typeof window === 'undefined' ? 'http://localhost:3000' : window.location.origin + const code = quickstartSnippet(lang, serverUrl, flagKey, sdkKey) + + async function copy() { + try { + await navigator.clipboard.writeText(code) + setCopied(true) + setTimeout(() => setCopied(false), 2000) + } catch { + // Clipboard unavailable (insecure origin): the text stays selectable. + } + } + + return ( +
+
+
+ {(['node', 'python'] as const).map((l) => ( + + ))} +
+ +
+
{code}
+
+ ) +} diff --git a/dashboard/src/components/Sidebar.tsx b/dashboard/src/components/Sidebar.tsx index fd2b1955..8867fc6e 100644 --- a/dashboard/src/components/Sidebar.tsx +++ b/dashboard/src/components/Sidebar.tsx @@ -8,6 +8,7 @@ import { Globe, ChevronDown, Activity, + FlaskRound, FolderKanban, Plus, Tags, @@ -69,6 +70,7 @@ const NAV_GROUPS: NavGroup[] = [ { to: '/experiments', icon: FlaskConical, label: 'Experiments' }, { to: '/exposure', icon: PieChart, label: 'Exposure' }, { to: '/impressions', icon: Activity, label: 'Impressions' }, + { to: '/playground', icon: FlaskRound, label: 'Playground' }, { to: '/audit', icon: History, label: 'Audit Log' }, { to: '/webhooks', icon: Webhook, label: 'Webhooks', adminOnly: true }, { to: '/integrations', icon: MessageSquare, label: 'Chat Alerts', adminOnly: true }, diff --git a/dashboard/src/pages/Dashboard.tsx b/dashboard/src/pages/Dashboard.tsx index d667217a..51ed747b 100644 --- a/dashboard/src/pages/Dashboard.tsx +++ b/dashboard/src/pages/Dashboard.tsx @@ -4,6 +4,7 @@ import { ToggleLeft, ToggleRight, ListFilter, CalendarClock, Plus, ArrowRight } import { api, scheduledApi } from '../api' import type { Flag, ScheduledChange } from '../types' import { useEnvironment } from '../context/EnvironmentContext' +import QuickstartSnippets from '../components/QuickstartSnippets' interface StatCardProps { label: string @@ -91,14 +92,27 @@ export default function Dashboard() { ) : error ? (
{error}
) : flags.length === 0 ? ( -
-

No flags yet.

- - Create your first flag - +
+

Get started in {activeEnv?.name ?? 'this environment'}

+
    +
  1. + + Create your first flag + {' '} + — call it new-checkout to match the snippet below. +
  2. +
  3. + Install an SDK and evaluate it. Set CHECKGATE_SDK_KEY to the key + from setup (or create one in project settings). +
    + +
    +
  4. +
  5. + Toggle the flag here: connected SDKs pick it up within a second. Check who gets what in the{' '} + Playground. +
  6. +
) : (
diff --git a/dashboard/src/pages/Playground.test.tsx b/dashboard/src/pages/Playground.test.tsx new file mode 100644 index 00000000..53db7a0c --- /dev/null +++ b/dashboard/src/pages/Playground.test.tsx @@ -0,0 +1,109 @@ +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { describe, it, expect, vi, beforeEach } from 'vitest' +import Playground, { exampleContext, parseAttributes } from './Playground' +import { api } from '../api' +import type { Flag, PlaygroundEvaluation } from '../types' + +vi.mock('../api', () => ({ + api: { listFlags: vi.fn(), evaluateFlag: vi.fn() }, +})) + +const ENV = { id: 'env-1', name: 'Development', color: '#4f46e5' } +const ENV_CTX = { environments: [ENV], activeEnv: ENV, setActiveEnv: vi.fn() } +vi.mock('../context/EnvironmentContext', () => ({ useEnvironment: () => ENV_CTX })) + +const FLAG: Flag = { + key: 'new-checkout', + is_enabled: true, + rollout_percentage: 30, + description: null, + rules: [ + { attribute: 'plan', operator: 'equals', values: ['pro', 'team'] }, + { attribute: 'country', operator: 'equals', values: ['PH'] }, + ], + flag_type: 'boolean', +} + +const RESULT: PlaygroundEvaluation = { + environment_id: 'env-1', + flag_key: 'new-checkout', + flag_type: 'boolean', + revision: 17, + enabled: true, + value: true, + reason: 'TARGETING_MATCH', + matched_rule: { + rule: { attribute: 'plan', operator: 'equals', values: ['pro', 'team'] }, + source_index: 0, + }, + prerequisites: [], + referenced_attributes: ['country', 'plan'], + missing_attributes: ['country'], +} + +describe('parseAttributes', () => { + it('accepts scalars and an empty editor', () => { + expect(parseAttributes('')).toEqual({ attributes: {} }) + expect(parseAttributes('{"plan":"pro","age":30,"beta":true}')).toEqual({ + attributes: { plan: 'pro', age: 30, beta: true }, + }) + }) + it('refuses invalid JSON, non-objects, nested values and too many attributes', () => { + for (const bad of ['{', '[1]', '"x"', 'null', '{"o":{"a":1}}', '{"n":null}', '{"l":[1]}']) { + expect(parseAttributes(bad).error, bad).toBeTruthy() + } + const many = JSON.stringify(Object.fromEntries(Array.from({ length: 101 }, (_, i) => [`a${i}`, 'v']))) + expect(parseAttributes(many).error).toMatch(/At most 100/) + }) +}) + +describe('exampleContext', () => { + it('uses the first value of each rule attribute', () => { + expect(exampleContext(FLAG)).toEqual({ plan: 'pro', country: 'PH' }) + expect(exampleContext(undefined)).toEqual({}) + }) +}) + +describe('Playground', () => { + beforeEach(() => { + vi.clearAllMocks() + vi.mocked(api.listFlags).mockResolvedValue([FLAG]) + vi.mocked(api.evaluateFlag).mockResolvedValue(RESULT) + }) + + it('evaluates on the server and explains the result', async () => { + const user = userEvent.setup() + render() + await waitFor(() => expect(screen.getByLabelText('Flag')).toHaveValue('new-checkout')) + await user.click(screen.getByRole('button', { name: /Example from this flag/ })) + await user.click(screen.getByRole('button', { name: /Evaluate/ })) + expect(api.evaluateFlag).toHaveBeenCalledWith('env-1', 'new-checkout', 'user-123', { plan: 'pro', country: 'PH' }) + expect(await screen.findByTestId('result-reason')).toHaveTextContent('TARGETING_MATCH') + expect(screen.getByTestId('result-state')).toHaveTextContent('ENABLED') + expect(screen.getByText(/#1: plan equals pro, team/)).toBeInTheDocument() + expect(screen.getByText('17')).toBeInTheDocument() + }) + + it('blocks evaluation while the attributes are invalid', async () => { + const user = userEvent.setup() + render() + await waitFor(() => expect(screen.getByLabelText('Flag')).toHaveValue('new-checkout')) + const editor = screen.getByLabelText('Attributes') + await user.clear(editor) + await user.type(editor, '{{"o": [1]}') + expect(screen.getByRole('alert')).toBeInTheDocument() + expect(screen.getByRole('button', { name: /Evaluate/ })).toBeDisabled() + expect(api.evaluateFlag).not.toHaveBeenCalled() + }) + + it('shows server errors and renders untrusted text as text', async () => { + vi.mocked(api.evaluateFlag).mockRejectedValue(new Error('')) + const user = userEvent.setup() + const { container } = render() + await waitFor(() => expect(screen.getByLabelText('Flag')).toHaveValue('new-checkout')) + await user.click(screen.getByRole('button', { name: /Evaluate/ })) + expect(await screen.findByRole('alert')).toHaveTextContent('') + expect(container.querySelector('img')).toBeNull() + }) +}) diff --git a/dashboard/src/pages/Playground.tsx b/dashboard/src/pages/Playground.tsx new file mode 100644 index 00000000..88609e90 --- /dev/null +++ b/dashboard/src/pages/Playground.tsx @@ -0,0 +1,334 @@ +import { useEffect, useMemo, useState } from 'react' +import { FlaskRound, Play, RotateCcw, AlertTriangle } from 'lucide-react' +import { api } from '../api' +import type { EvaluationReason, Flag, FlagValue, PlaygroundEvaluation, TargetingRule } from '../types' +import { useEnvironment } from '../context/EnvironmentContext' + +// --------------------------------------------------------------------------- +// Evaluation playground: "what would an SDK answer for this user?" +// +// The evaluation runs on the server with the SDK engine and the configuration +// revision SDKs are served. Nothing here re-implements targeting: this page +// only collects a context and displays the explanation. Nothing is stored. +// --------------------------------------------------------------------------- + +const MAX_ATTRIBUTES = 100 + +const REASON_TEXT: Record = { + DISABLED: 'The flag is switched off.', + PREREQUISITE_FAILED: 'A prerequisite flag is not satisfied, so the flag resolves as off.', + TARGETING_MATCH: 'A targeting rule matched.', + ROLLOUT_EXCLUDED: 'The user is outside the percentage rollout.', + SPLIT: 'Hashing the user key decided: inside a partial rollout, or a weighted variant.', + DEFAULT: 'The flag has rules, none matched: the default value.', + STATIC: 'No rules, partial rollout or variants: every user gets this value.', +} + +type Attributes = Record + +/** Parses the attributes editor; returns an error message instead of throwing. */ +export function parseAttributes(text: string): { attributes?: Attributes; error?: string } { + if (text.trim() === '') return { attributes: {} } + let parsed: unknown + try { + parsed = JSON.parse(text) + } catch { + return { error: 'Attributes must be valid JSON, e.g. {"plan": "pro"}.' } + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + return { error: 'Attributes must be a JSON object.' } + } + const entries = Object.entries(parsed as Record) + if (entries.length > MAX_ATTRIBUTES) return { error: `At most ${MAX_ATTRIBUTES} attributes.` } + const attributes: Attributes = {} + for (const [name, value] of entries) { + if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') { + return { error: `"${name}" must be a string, number or boolean.` } + } + attributes[name] = value + } + return { attributes } +} + +/** An example context that exercises each of the flag's own rules. */ +export function exampleContext(flag: Flag | undefined): Attributes { + const out: Attributes = {} + for (const rule of flag?.rules ?? []) { + if (rule.attribute && rule.values?.length && !(rule.attribute in out)) { + out[rule.attribute] = rule.values[0] + } + } + return out +} + +function describeRule(rule: TargetingRule): string { + if (rule.segment_key) return `in segment “${rule.segment_key}”` + return `${rule.attribute} ${rule.operator.replace(/_/g, ' ')} ${rule.values.join(', ')}` +} + +function formatValue(value: FlagValue | undefined): string { + if (value === undefined) return '—' + return typeof value === 'string' ? JSON.stringify(value) : JSON.stringify(value, null, 2) +} + +function valueType(value: FlagValue): string { + if (value === null) return 'null' + if (Array.isArray(value)) return 'array' + return typeof value +} + +function Row({ label, children }: { label: string; children: React.ReactNode }) { + return ( +
+ {label} +
{children}
+
+ ) +} + +export default function Playground() { + const { activeEnv } = useEnvironment() + const [flags, setFlags] = useState([]) + const [flagKey, setFlagKey] = useState('') + const [targetingKey, setTargetingKey] = useState('user-123') + const [attributesText, setAttributesText] = useState('{}') + const [result, setResult] = useState(null) + const [error, setError] = useState(null) + const [loading, setLoading] = useState(false) + + useEffect(() => { + setFlags([]) + setFlagKey('') + setResult(null) + if (!activeEnv) return + let cancelled = false + api + .listFlags(activeEnv.id) + .then(list => { + if (cancelled) return + setFlags(list) + setFlagKey(list[0]?.key ?? '') + }) + .catch(e => !cancelled && setError(e instanceof Error ? e.message : String(e))) + return () => { + cancelled = true + } + }, [activeEnv]) + + const flag = useMemo(() => flags.find(f => f.key === flagKey), [flags, flagKey]) + const parsed = useMemo(() => parseAttributes(attributesText), [attributesText]) + + const reset = () => { + setTargetingKey('user-123') + setAttributesText('{}') + setResult(null) + setError(null) + } + + const evaluate = async () => { + if (!activeEnv || !flagKey || parsed.error || !parsed.attributes) return + setLoading(true) + setError(null) + try { + setResult(await api.evaluateFlag(activeEnv.id, flagKey, targetingKey, parsed.attributes)) + } catch (e) { + setResult(null) + setError(e instanceof Error ? e.message : String(e)) + } finally { + setLoading(false) + } + } + + const inputClass = + 'w-full bg-white border border-gray-100 rounded-xl px-4 py-2.5 text-sm text-gray-900 focus:outline-none focus:ring-4 focus:ring-brand-500/10 focus:border-brand-500/30 transition-all' + + return ( +
+
+
+
+ +
+
+

Evaluation Playground

+

+ See what an SDK would answer for a user in {activeEnv?.name ?? '…'}, and why. + Evaluated on the server with the SDK engine; nothing is changed or stored. +

+
+
+
+ +
+ {/* Left: context */} +
+ + + + +