Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/slim-bootstrap-snapshots.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@reflag/node-sdk": patch
"@reflag/browser-sdk": patch
"@reflag/react-sdk": patch
---

Return smaller, JSON-safe bootstrap snapshots that remain compatible with existing v2 clients. Updated clients also accept bootstrap snapshots without `ruleResults`; flag values and exposure tracking are unchanged.
47 changes: 35 additions & 12 deletions packages/browser-sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ import {
} from "./feedback/feedback";
import * as feedbackLib from "./feedback/ui";
import { isValidBootstrapSnapshot } from "./flag/bootstrap";
import { CheckEvent, FlagsClient, OptInFlag, RawFlags } from "./flag/flags";
import {
type BootstrappedState,
CheckEvent,
FlagsClient,
OptInFlag,
RawFlags,
} from "./flag/flags";
import { isValidFlagStateVersion } from "./flag/flagStateVersion";
import {
FlagDefaultValue,
Expand Down Expand Up @@ -220,15 +226,7 @@ export type ToolbarOptions =
*/
export type FlagDefinitions = Readonly<Array<string>>;

/**
* Pre-fetched evaluated state used to bootstrap the client.
*/
export type BootstrappedState = {
protocolVersion: 2;
context: ReflagContext;
flags: RawFlags;
flagStateVersion?: number;
};
export type { BootstrappedState } from "./flag/flags";

/**
* ReflagClient initialization options.
Expand Down Expand Up @@ -1150,11 +1148,36 @@ export class ReflagClient {
}

getFlagsForBootstrap(): BootstrappedState {
const flagStateVersion = this.flagsClient.getFlagStateVersion();
const flags = Object.fromEntries(
Object.entries(this.getFlagResults()).map(([key, flag]) => [
key,
{
resolved: flag.resolved,
...(flag.value === undefined ? {} : { value: flag.value }),
...(flag.variantKey === undefined ||
flag.sourceVersionId === undefined
? {}
: {
variantKey: flag.variantKey,
sourceVersionId: flag.sourceVersionId,
}),
ruleResults: flag.ruleResults.map(({ ruleId, matched }) => ({
ruleId,
matched,
})),
errors: flag.errors,
...(flag.optInEnabled === undefined
? {}
: { optInEnabled: flag.optInEnabled, optIn: flag.optIn }),
},
]),
);
return {
protocolVersion: 2,
context: this.getContext(),
flags: this.getFlagResults(),
flagStateVersion: this.flagsClient.getFlagStateVersion(),
flags,
...(flagStateVersion === undefined ? {} : { flagStateVersion }),
};
}

Expand Down
7 changes: 4 additions & 3 deletions packages/browser-sdk/src/flag/flagCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,9 @@ export function parseAPIFlagsResponse(
isFlagValue(flag.value) ||
(bootstrap && flag.resolved === false && flag.value === undefined)
) ||
!Array.isArray(flag.ruleResults) ||
!flag.ruleResults.every(isRuleEvaluationResult) ||
(!(bootstrap && flag.ruleResults === undefined) &&
(!Array.isArray(flag.ruleResults) ||
!flag.ruleResults.every(isRuleEvaluationResult))) ||
!Array.isArray(flag.errors) ||
!flag.errors.every(isEvaluationError) ||
(flag.matchedRuleId !== undefined &&
Expand Down Expand Up @@ -111,7 +112,7 @@ export function parseAPIFlagsResponse(
sourceVersionId: flag.sourceVersionId,
matchedRuleId: flag.matchedRuleId,
allocationIndex: flag.allocationIndex,
ruleResults: flag.ruleResults,
ruleResults: flag.ruleResults ?? [],
errors: flag.errors,
...(flag.optInEnabled === undefined
? {}
Expand Down
16 changes: 11 additions & 5 deletions packages/browser-sdk/src/flag/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,14 +179,20 @@ const REFRESH_LIMIT_WINDOW_MS = 60 * 1000;

export type FlagOverrides = Record<string, FlagValue | undefined>;

type BootstrappedState = {
/** Pre-fetched evaluated state used to bootstrap the client. */
export type BootstrappedState = {
protocolVersion: 2;
flags: RawFlags;
context: ReflagContext;
flags: Record<
string,
Omit<RawFlag, "value" | "ruleResults"> &
Partial<Pick<RawFlag, "value" | "ruleResults">>
>;
flagStateVersion?: number;
};

type FlagsClientOptions = Partial<Config> & {
bootstrappedState?: BootstrappedState;
bootstrappedState?: Omit<BootstrappedState, "context">;
cache?: FlagCache;
rateLimiter?: RateLimiter;
storage?: StorageAdapter;
Expand Down Expand Up @@ -476,7 +482,7 @@ export class FlagsClient {
}

setFetchedFlags(
fetchedFlags: RawFlags,
fetchedFlags: BootstrappedState["flags"],
triggerEvent = true,
flagStateVersion?: number,
) {
Expand All @@ -495,7 +501,7 @@ export class FlagsClient {
// A newly accepted snapshot supersedes any metadata-only request in flight.
this.optInMetadataFetchVersion++;
this.setOptInMetadata(validated, flagStateVersion);
this.warnMissingFlagContextFields(fetchedFlags);
this.warnMissingFlagContextFields(validated);
this.updateFlags(triggerEvent);
}

Expand Down
82 changes: 80 additions & 2 deletions packages/browser-sdk/test/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";

import type { BulkEvent } from "../src/bulkQueue";
import { BootstrappedState, ReflagClient } from "../src/client";
import { RawFlags } from "../src/flag/flags";
import { flagResponse, selectedFlag } from "./mocks/handlers";
import { server } from "./mocks/server";
import { testLogger } from "./testLogger";
Expand Down Expand Up @@ -40,7 +39,10 @@ function create(
clients.push(client);
return client;
}
function bootstrap(flags: RawFlags, flagStateVersion = 1): BootstrappedState {
function bootstrap(
flags: BootstrappedState["flags"],
flagStateVersion = 1,
): BootstrappedState {
return {
protocolVersion: 2,
context: { user: { id: "alice" }, company: { id: "acme" } },
Expand Down Expand Up @@ -95,6 +97,29 @@ describe("direct values and root checks", () => {
},
);

test("bootstraps and records the selected variant without rule results", async () => {
const client = create({
bootstrappedState: bootstrap({
flagA: {
value: "enhanced",
resolved: true,
variantKey: "enhanced",
sourceVersionId: "bootstrap-version",
errors: [],
},
}),
});
expect(client.getFlagResults().flagA.ruleResults).toEqual([]);
expect(client.getFlag("flagA", "default")).toBe("enhanced");
await client.stop();
expect(checks()[0]).toMatchObject({
key: "flagA",
evalResult: "enhanced",
sourceVersionId: "bootstrap-version",
evalRuleResults: [],
});
});

test("forwards v2 diagnostics without adding initialization errors to bootstrap reads", async () => {
const error = {
code: "MISSING_CONTEXT_FIELD",
Expand All @@ -112,6 +137,59 @@ describe("direct values and root checks", () => {
expect(checks()[0].evalErrors).toEqual([error]);
});

test("reserializes only bootstrap fields without losing check metadata", async () => {
const client = create({
bootstrappedState: {
protocolVersion: 2,
context: { user: { id: "alice" } },
flags: {
flagA: {
...selectedFlag(null, "none"),
matchedRuleId: "split",
allocationIndex: 0,
ruleResults: [
{ ruleId: "skipped", matched: false },
{
ruleId: "split",
matched: true,
allocationIndex: 0,
destination: { type: "variant", variantKey: "none" },
},
],
},
unresolved: { resolved: false, ruleResults: [], errors: [] },
},
},
});
expect(client.getFlagResults().flagA.allocationIndex).toBe(0);
const state = client.getFlagsForBootstrap();
expect(state).toStrictEqual(JSON.parse(JSON.stringify(state)));
expect(state).not.toHaveProperty("flagStateVersion");
expect(state.flags.flagA).toStrictEqual({
value: null,
resolved: true,
variantKey: "none",
sourceVersionId: "version-1",
ruleResults: [
{ ruleId: "skipped", matched: false },
{ ruleId: "split", matched: true },
],
errors: [],
});
expect(state.flags.unresolved).not.toHaveProperty("value");

const restored = create({ bootstrappedState: state });
expect(restored.getFlag("flagA", null)).toBeNull();
expect(restored.getFlag("unresolved", "fallback")).toBe("fallback");
await restored.stop();
expect(checks()[0]).toMatchObject({
key: "flagA",
evalResult: "none",
sourceVersionId: "version-1",
evalRuleResults: [false, true],
});
});

test("registers an ignored root read immediately, but diagnostics/bootstrap register none; delivery stays buffered", async () => {
const client = create();
const check = vi.fn();
Expand Down
24 changes: 18 additions & 6 deletions packages/browser-sdk/test/flagCache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,22 @@ describe("v2 evaluated cache", () => {
expect(parseAPIFlagsResponse(flags)).toEqual(flags);
});

test("accepts omitted rule results only in bootstrap snapshots", () => {
const { ruleResults: _ruleResults, ...flagA } = selectedFlag(true);
expect(parseAPIFlagsResponse({ flagA }, true)).toEqual({
flagA: { ...flagA, ruleResults: [] },
});
expect(parseAPIFlagsResponse({ flagA })).toBeUndefined();
expect(
parseAPIFlagsResponse({ flagA: { ...flagA, ruleResults: null } }, true),
).toBeUndefined();
});

test.each([
null,
true,
{},
{ ...rule, ruleId: null },
{ ...rule, ruleId: 1 },
{ ...rule, matched: undefined },
{ ...rule, matched: 1 },
Expand All @@ -72,12 +84,12 @@ describe("v2 evaluated cache", () => {
{ type: "variant", variantKey: 1 },
].map((destination) => ({ ...rule, destination })),
])("rejects malformed rule diagnostics atomically: %j", (invalidRule) => {
expect(
parseAPIFlagsResponse({
good: selectedFlag(true),
bad: { ...selectedFlag(true), ruleResults: [invalidRule] },
}),
).toBeUndefined();
const flags = {
good: selectedFlag(true),
bad: { ...selectedFlag(true), ruleResults: [invalidRule] },
};
expect(parseAPIFlagsResponse(flags)).toBeUndefined();
expect(parseAPIFlagsResponse(flags, true)).toBeUndefined();
});

test.each([
Expand Down
6 changes: 4 additions & 2 deletions packages/node-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -422,8 +422,10 @@ console.log(bootstrappedState);
// "huddle-settings": {
// "value": { "maxParticipants": 50, "videoQuality": "hd" },
// "variantKey": "enhanced",
// "sourceVersionId": "example-version",
// "resolved": true,
// ...
// "ruleResults": [{ "ruleId": "example-rule", "matched": true }],
// "errors": []
// }
// },
// flagStateVersion: 42
Expand All @@ -447,7 +449,7 @@ const bootstrappedState = boundClient.getFlagsForBootstrap();

### Key differences from `getFlags()`

- **Raw data**: Returns the evaluated raw flags, including their values and evaluation details, as JSON serializable objects
- **Bootstrap data**: Returns JSON-safe flag values and the metadata needed to record checks in the client, without the full evaluation trace
- **Public flags only**: Leaves out flags that aren't marked `secret: false`
- **No checks**: Doesn't record `check` events
- **Context included**: Returns both the evaluated flags and the context used for evaluation
Expand Down
38 changes: 25 additions & 13 deletions packages/node-sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -516,19 +516,31 @@ export class ReflagClient {
.filter((flag) => flag.secret === false)
.map((flag) => flag.key),
);
const publicFlags = Object.fromEntries(
Object.entries(flags)
.filter(([key]) => publicKeys.has(key))
.map(([key, result]) => [
key,
{
...result,
// Match publishable-key HTTP evaluation: dependency origins can name
// private flags or segments, even when the requested root is public.
errors: result.errors.map(({ source: _source, ...error }) => error),
},
]),
);
const publicFlags: BootstrappedFlags["flags"] = Object.create(null);
for (const [key, result] of Object.entries(flags)) {
// Omit entries without a value. Reads still use their fallback, and v2
// client types expect each entry to have a value property.
if (!publicKeys.has(key) || result.value === undefined) continue;
publicFlags[key] = {
resolved: result.resolved,
value: result.value,
...(result.resolved &&
result.variantKey !== undefined &&
result.sourceVersionId !== undefined
? {
variantKey: result.variantKey,
sourceVersionId: result.sourceVersionId,
}
: {}),
// Released v2 readers require the array and its rule IDs.
ruleResults: result.ruleResults.map(({ ruleId, matched }) => ({
ruleId,
matched,
})),
// Dependency origins can name private flags or segments.
errors: result.errors.map(({ source: _source, ...error }) => error),
};
}
return {
protocolVersion: 2,
context: JSON.parse(
Expand Down
9 changes: 8 additions & 1 deletion packages/node-sdk/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,14 @@ export type RawFlags = Record<string, RawFlag>;
export type BootstrappedFlags = {
protocolVersion: 2;
context: Context;
flags: RawFlags;
flags: Record<
string,
Pick<RawFlag, "resolved" | "variantKey" | "sourceVersionId"> & {
value: FlagValue;
ruleResults: Pick<RawFlag["ruleResults"][number], "ruleId" | "matched">[];
errors: (EvaluationError & { source?: never })[];
}
>;
flagStateVersion?: number;
};
export type EvaluatedFlagsAPIResponse = {
Expand Down
Loading
Loading