Skip to content

Commit 6473edb

Browse files
authored
Merge pull request #353 from better-stack-ai/feat/issue-342-after-v6
feat(feature-flags): add weighted variants and evaluation hook
2 parents 7f8a254 + 8625494 commit 6473edb

21 files changed

Lines changed: 845 additions & 51 deletions

File tree

‎docs/content/docs/plugins/feature-flags.mdx‎

Lines changed: 74 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,8 @@ rules: ({ featureFlags }) => [
8989
],
9090
```
9191

92-
Evaluation operations and HTTP endpoints are public: they expose boolean results
92+
Evaluation operations and HTTP endpoints are public: they expose boolean results,
93+
assigned variant keys, and assigned payloads
9394
and do not consult authorization rules. Bulk evaluation also exposes active flag
9495
keys. Their permission facts distinguish `scope: "single"` with a `key` from
9596
`scope: "all"`, but those descriptors do not restrict public access. Browser
@@ -128,6 +129,52 @@ Disabled, archived, and missing flags evaluate to `false`. Keys remain reserved
128129
when archived. Segment flags require at least one rule. Organizing tags on the
129130
flag definition are separate from targeting tags supplied in evaluation context.
130131

132+
## Weighted variants
133+
134+
Any flag type can define optional weighted alternatives. Existing boolean
135+
evaluations are unchanged: variants are assigned only after the flag evaluates to
136+
`true`. Use the dashboard's **Variants** controls to add keys, weights, and optional
137+
JSON payloads, then **Preview saved variants** to try a user or session and see
138+
the assignment in the evaluation log.
139+
140+
```ts
141+
await myStack.trusted.featureFlags.createFlag({
142+
key: "checkout-layout",
143+
name: "Checkout layout",
144+
enabled: true,
145+
variants: [
146+
{ key: "control", weight: 30, payload: "classic" },
147+
{ key: "compact", weight: 70, payload: { columns: 1 } },
148+
],
149+
})
150+
151+
const { result, variant, payload } = await myStack.forRequest(request)
152+
.operations.featureFlags.evaluateVariant({
153+
key: "checkout-layout",
154+
context: { userId: session.userId },
155+
})
156+
```
157+
158+
Variant keys must be unique, non-empty strings of up to 100 characters.
159+
Weights are finite numbers from 0 to 100 and must sum to 100, including decimal
160+
weights. Zero-weight alternatives receive no assignments. An empty `variants`
161+
array removes variants. Payloads may be strings, numbers, booleans, or JSON
162+
objects (including nested arrays and nulls); top-level arrays and null are not
163+
accepted. Payloads are public to evaluation clients; never store secrets in them.
164+
165+
Assignment uses the flag key and `userId`, falling back to `sessionId`, then
166+
`anonymous`, in a separate bucket from percentage rollout. The same definition
167+
and identity produce the same assignment on server, browser, and edge. Editing
168+
weights, keys, or ordering can reassign subjects. Disabled, archived, missing,
169+
untargeted flags and flags without variants return `variant: null` without a
170+
payload. `result` still reports boolean eligibility.
171+
172+
The pure `evaluateFlagVariant(flag, context)` export from
173+
`@btst/plugin-feature-flags/evaluate` returns the same assignment without logs or
174+
hooks. Database users must apply their adapter's additive schema migration for
175+
the new serialized `flag.variants` string field (default `"[]"`). Existing records
176+
without variants are read as empty lists; existing rollout buckets are preserved.
177+
131178
## Server-side evaluation
132179

133180
Use request-scoped operations in Server Components and API routes. Evaluation is
@@ -183,14 +230,29 @@ flag read permission. The same hooks entry exports create, update, toggle, archi
183230
and evaluation-log hooks. Management mutations invalidate cached definitions,
184231
values, and logs in the current query client.
185232

233+
`useFeatureFlagVariant` returns a React Query result with the boolean result,
234+
assigned key, and optional payload. It uses the same identity and transport cache
235+
partitioning and visible-tab refresh interval as `useFlag`. Definition edits
236+
invalidate both hooks immediately in the current query client.
237+
238+
```tsx
239+
import { useFeatureFlagVariant } from "@btst/plugin-feature-flags/client/hooks"
240+
241+
const { data, isPending, error } = useFeatureFlagVariant("checkout-layout", { userId })
242+
if (isPending) return <p>Loading layout…</p>
243+
if (error) return <p>Layout could not be loaded.</p>
244+
return data?.variant === "compact" ? <CompactCheckout /> : <ClassicCheckout />
245+
```
246+
186247
## HTTP evaluation
187248

188249
| Method | Endpoint | Result |
189250
| --- | --- | --- |
190251
| GET | `/api/data/feature-flags/evaluate/:key` | Boolean |
191252
| GET | `/api/data/feature-flags/evaluate` | Object mapping active flag keys to booleans |
253+
| GET | `/api/data/feature-flags/variant/:key` | `{ result: boolean, variant: string \| null, payload?: ... }` |
192254

193-
Both endpoints accept an optional `context` query parameter containing base64
255+
All evaluation endpoints accept an optional `context` query parameter containing base64
194256
encoded UTF-8 JSON, such as `{ "userId": "user-123", "tags": ["beta"] }`. Invalid
195257
context is rejected. Definitions and evaluation logs use separate protected
196258
management endpoints under `/api/data/feature-flags/flags`.
@@ -210,6 +272,16 @@ have separate histories. Use `hooks.onEvaluate` to send exposures to your analyt
210272
audit system when persistent storage is required. Hooks run after authorization;
211273
`onBeforeToggle` can throw to prevent a toggle.
212274

275+
Every evaluation path (including boolean and bulk evaluation) records the assigned
276+
`variant` key or `null` in `FlagEvaluation`. The existing `onEvaluate` callback
277+
keeps its argument order; its fourth argument now includes `variant`:
278+
279+
```ts
280+
onEvaluate: (flag, result, context, { request, variant }) => {
281+
analytics.capture({ flag: flag.key, result, variant, userId: context.userId })
282+
}
283+
```
284+
213285
## SSG and ISR
214286

215287
Administration is dynamic. A static consumer can evaluate trusted flag values at

‎e2e/tests/smoke.feature-flags.spec.ts‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,130 @@
11
import { expect, test } from "@playwright/test";
22
import { mockAuthHeaders, setMockAuthCookie } from "./helpers/mock-auth";
33

4+
test("authors weighted variants, previews deterministic assignments and refreshes edits", async ({
5+
page,
6+
request,
7+
}) => {
8+
const key = `variants-${Date.now()}`;
9+
const base = "/api/data/feature-flags";
10+
await setMockAuthCookie(page.context());
11+
await page.goto("/pages/feature-flags/new");
12+
await page.getByLabel("Name", { exact: true }).fill("Checkout variants");
13+
await page.getByLabel("Key", { exact: true }).fill(key);
14+
await page.getByLabel("Enable on creation").check();
15+
await page.getByRole("button", { name: "Add variant", exact: true }).click();
16+
const first = page.getByRole("group", { name: "Variant 1", exact: true });
17+
await first.getByLabel("Variant key").fill("control");
18+
await first.getByLabel("Weight (%)").fill("40");
19+
await first.getByLabel("Payload (JSON)").fill('"classic"');
20+
await page.getByRole("button", { name: "Add variant", exact: true }).click();
21+
const second = page.getByRole("group", { name: "Variant 2", exact: true });
22+
await second.getByLabel("Variant key").fill("compact");
23+
await second.getByLabel("Weight (%)").fill("50");
24+
await second.getByLabel("Payload (JSON)").fill('{"columns":1}');
25+
await page.getByRole("button", { name: "Create flag", exact: true }).click();
26+
await expect(
27+
page
28+
.getByRole("alert")
29+
.filter({ hasText: "Variant weights must sum to 100" }),
30+
).toBeVisible();
31+
await second.getByLabel("Weight (%)").fill("60");
32+
await page.getByRole("button", { name: "Create flag", exact: true }).click();
33+
const row = page
34+
.getByRole("list", { name: "Feature flags", exact: true })
35+
.locator(":scope > li")
36+
.filter({ hasText: key });
37+
await row
38+
.getByRole("link", { name: "Checkout variants", exact: true })
39+
.click();
40+
await expect(first.getByLabel("Weight (%)")).toHaveValue("40");
41+
await expect(second.getByLabel("Payload (JSON)")).toHaveValue(
42+
'{"columns":1}',
43+
);
44+
await page.getByRole("link", { name: "Preview saved variants" }).click();
45+
await page.getByLabel("User ID", { exact: true }).fill("repeat-user");
46+
await page
47+
.getByRole("button", { name: "Evaluate flag", exact: true })
48+
.click();
49+
await expect(page.getByRole("status")).toContainText(
50+
"Result: true | Variant:",
51+
);
52+
const context = Buffer.from(
53+
JSON.stringify({ userId: "repeat-user" }),
54+
).toString("base64");
55+
const value = await (
56+
await request.get(`${base}/variant/${key}`, { params: { context } })
57+
).json();
58+
expect(["control", "compact"]).toContain(value.variant);
59+
await expect(page.getByRole("status")).toContainText(
60+
`Variant: ${value.variant}`,
61+
);
62+
expect(
63+
await (
64+
await request.get(`${base}/variant/${key}`, { params: { context } })
65+
).json(),
66+
).toEqual(value);
67+
expect(
68+
await (
69+
await request.get(`${base}/evaluate/${key}`, { params: { context } })
70+
).json(),
71+
).toBe(true);
72+
const denied = await request.patch(`${base}/flags/${key}`, {
73+
data: { variants: [] },
74+
});
75+
expect([401, 403]).toContain(denied.status());
76+
const headers = mockAuthHeaders();
77+
const logs = await (
78+
await request.get(`${base}/flags/${key}/log`, { headers })
79+
).json();
80+
expect(logs).toContainEqual(
81+
expect.objectContaining({
82+
variant: value.variant,
83+
context: { userId: "repeat-user" },
84+
}),
85+
);
86+
await page.goto(`/pages/feature-flags/${key}`);
87+
await first.getByLabel("Weight (%)").fill("0");
88+
await second.getByLabel("Weight (%)").fill("100");
89+
await page.getByRole("button", { name: "Save changes", exact: true }).click();
90+
await expect(page.getByText("Flag saved", { exact: true })).toBeVisible();
91+
expect(
92+
await (
93+
await request.get(`${base}/variant/${key}`, { params: { context } })
94+
).json(),
95+
).toEqual({ result: true, variant: "compact", payload: { columns: 1 } });
96+
await page.getByRole("link", { name: "Preview saved variants" }).click();
97+
await page.getByLabel("User ID", { exact: true }).fill("repeat-user");
98+
await page
99+
.getByRole("button", { name: "Evaluate flag", exact: true })
100+
.click();
101+
await expect(page.getByRole("status")).toContainText(
102+
'Variant: compact | Payload: {"columns":1}',
103+
);
104+
await request.patch(`${base}/flags/${key}`, {
105+
headers,
106+
data: {
107+
variants: [{ key: "compact", weight: 100, payload: "x".repeat(250) }],
108+
},
109+
});
110+
await page.setViewportSize({ width: 390, height: 844 });
111+
await page.reload();
112+
await page.getByLabel("User ID", { exact: true }).fill("repeat-user");
113+
await page
114+
.getByRole("button", { name: "Evaluate flag", exact: true })
115+
.click();
116+
await expect(page.getByRole("status")).toContainText("x".repeat(250));
117+
expect(
118+
await page.evaluate(() => document.documentElement.scrollWidth),
119+
).toBeLessThanOrEqual(390);
120+
await request.post(`${base}/flags/${key}/archive`, { headers });
121+
expect(
122+
await (
123+
await request.get(`${base}/variant/${key}`, { params: { context } })
124+
).json(),
125+
).toEqual({ result: false, variant: null });
126+
});
127+
4128
test("feature flags protect management and update live evaluations through the dashboard", async ({
5129
page,
6130
request,

0 commit comments

Comments
 (0)