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
9 changes: 9 additions & 0 deletions .changeset/remove-fallback-flags.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@reflag/browser-sdk": major
"@reflag/react-sdk": major
"@reflag/vue-sdk": major
"@reflag/react-native-sdk": major
"@reflag/node-sdk": major
---

Remove the `fallbackFlags` option. Pass a default to each flag read instead, for example `useFlag("huddles", true)` or `getFlag("model", "quick")`; it's returned whenever the flag has no value. On the server, use a fallback provider to keep evaluating flags when Reflag can't be reached.
15 changes: 1 addition & 14 deletions packages/browser-sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,7 @@ import {
} from "./feedback/feedback";
import * as feedbackLib from "./feedback/ui";
import { isValidBootstrapSnapshot } from "./flag/bootstrap";
import {
CheckEvent,
FallbackFlagOverride,
FlagsClient,
OptInFlag,
RawFlags,
} from "./flag/flags";
import { CheckEvent, FlagsClient, OptInFlag, RawFlags } from "./flag/flags";
import { isValidFlagStateVersion } from "./flag/flagStateVersion";
import {
FlagDefaultValue,
Expand Down Expand Up @@ -270,12 +264,6 @@ export type InitOptions = ReflagDeprecatedContext & {
*/
offline?: boolean;

/**
* Value-only startup fallbacks. An array enables the listed Boolean flags.
* Fallback values never identify an authored selection.
*/
fallbackFlags?: string[] | Record<string, FallbackFlagOverride>;

/**
* Timeout in milliseconds when fetching flags
*/
Expand Down Expand Up @@ -577,7 +565,6 @@ export class ReflagClient {
staleTimeMs: opts.staleTimeMs,
staleWhileRevalidate: opts.staleWhileRevalidate,
timeoutMs: opts.timeoutMs,
fallbackFlags: opts.fallbackFlags,
offline: this.config.offline,
storage: opts.storage,
enqueueBulkEvent: bulkQueue
Expand Down
44 changes: 2 additions & 42 deletions packages/browser-sdk/src/flag/flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,6 @@ export type RawFlag = {
};
export type RawFlags = Record<string, RawFlag>;
export type FlagValues = Record<string, FlagValue | undefined>;
export type FallbackFlagOverride = FlagValue;
type FallbackFlags = Record<string, FlagValue>;

type Config = {
timeoutMs: number;
Expand Down Expand Up @@ -189,7 +187,6 @@ type BootstrappedState = {

type FlagsClientOptions = Partial<Config> & {
bootstrappedState?: BootstrappedState;
fallbackFlags?: Record<string, FallbackFlagOverride> | string[];
cache?: FlagCache;
rateLimiter?: RateLimiter;
storage?: StorageAdapter;
Expand All @@ -214,7 +211,6 @@ export class FlagsClient {
private fetchedFlagsContextVersion = 0;
private flagOverrides: FlagOverrides = {};
private flags: RawFlags = {};
private fallbackFlags: FallbackFlags = {};
private contextFetchVersion = 0;
private optInMetadata: Record<string, RawFlagOptIn> = Object.create(null);
private lastUpdatedOptInMetadata: Record<string, RawFlagOptIn> =
Expand Down Expand Up @@ -250,7 +246,6 @@ export class FlagsClient {
bootstrappedState,
cache,
rateLimiter,
fallbackFlags,
storage,
enqueueBulkEvent,
...config
Expand All @@ -272,7 +267,6 @@ export class FlagsClient {
this.cache =
cache ??
this.setupCache(this.config.staleTimeMs, this.config.expireTimeMs);
this.fallbackFlags = this.setupFallbackFlags(fallbackFlags);

if (bootstrappedState) {
if (!isValidBootstrapSnapshot(bootstrappedState)) {
Expand Down Expand Up @@ -841,7 +835,7 @@ export class FlagsClient {
private async maybeFetchFlags(
requestContextVersion = this.contextFetchVersion,
): Promise<FetchedFlagsResult> {
if (this.config.offline) return this.fallbackResult();
if (this.config.offline) return { flags: {} };

const cacheKey = this.fetchParams().toString();
const cachedItem = await this.cache.get(cacheKey);
Expand Down Expand Up @@ -892,23 +886,7 @@ export class FlagsClient {
flags: this.fetchedFlags,
flagStateVersion: this.fetchedFlagStateVersion,
};
return this.fallbackResult();
}

private fallbackResult(): FetchedFlagsResult {
return {
flags: Object.fromEntries(
Object.entries(this.fallbackFlags).map(([key, value]) => [
key,
{
value: copyJSON(value),
resolved: false,
ruleResults: [],
errors: [],
},
]),
),
};
return { flags: {} };
Comment thread
roncohen marked this conversation as resolved.
Resolved
}

/** Bootstrap may omit opt-in metadata. Fetch only the missing metadata without
Expand Down Expand Up @@ -1035,24 +1013,6 @@ export class FlagsClient {
});
}

private setupFallbackFlags(
fallbackFlags?: Record<string, FallbackFlagOverride> | string[],
) {
if (Array.isArray(fallbackFlags)) {
return fallbackFlags.reduce(
(acc, key) => {
acc[key] = true;
return acc;
},
{} as Record<string, FallbackFlagOverride>,
);
} else {
if (fallbackFlags !== undefined && !isFlagValue(fallbackFlags))
throw new Error("fallbackFlags must contain JSON values");
return copyJSON(fallbackFlags ?? {});
}
}

private fetchParams() {
const contextJson = canonicalContextJSONStringify(this.context);
const params = new URLSearchParams(
Expand Down
1 change: 0 additions & 1 deletion packages/browser-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ export type {
} from "./feedback/ui/types";
export type {
CheckEvent,
FallbackFlagOverride,
FlagOverrides,
FlagValues,
EvaluationError,
Expand Down
14 changes: 7 additions & 7 deletions packages/browser-sdk/test/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,15 +323,15 @@ describe("direct values and root checks", () => {
});
});

test("offline uses direct static fallbacks without fetching or tracking", async () => {
test("offline returns read defaults without fetching or tracking", async () => {
const fetch = vi.spyOn(globalThis, "fetch");
const client = create({
offline: true,
fallbackFlags: { release: true, settings: { model: "offline" } },
});
const client = create({ offline: true });
await client.initialize();
expect(client.getFlag("release")).toBe(true);
expect(client.getFlag("settings", null)).toEqual({ model: "offline" });
expect(client.getFlag("release")).toBe(false);
expect(client.getFlag("release", true)).toBe(true);
expect(client.getFlag("settings", { model: "offline" })).toEqual({
model: "offline",
});
await client.stop();
expect(fetch).not.toHaveBeenCalled();
});
Expand Down
16 changes: 3 additions & 13 deletions packages/browser-sdk/test/flags.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -492,21 +492,11 @@ describe("v2 snapshots", () => {
},
);

test("falls back to unselected direct JSON after an initial HTTP failure", async () => {
const { client, get } = setup({
fallbackFlags: { settings: { model: "offline" }, false: false },
});
test("has no flags after an initial HTTP failure with nothing cached", async () => {
const { client, get } = setup();
get.mockResolvedValue(Response.json({}, { status: 503 }));
await client.initialize();
expect(client.getFlags()).toEqual({
settings: {
value: { model: "offline" },
resolved: false,
ruleResults: [],
errors: [],
},
false: { value: false, resolved: false, ruleResults: [], errors: [] },
});
expect(client.getFlags()).toEqual({});
});

test("storage failure does not discard a successful live response", async () => {
Expand Down
12 changes: 0 additions & 12 deletions packages/node-sdk/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,13 +218,6 @@ export class ReflagClient {
);
this.httpClient = options.httpClient ?? fetchClient;
this.baseOverrides = normalizeOverrides(config.flagOverrides);
const fallbackFlags = Array.isArray(options.fallbackFlags)
? Object.fromEntries(options.fallbackFlags.map((key) => [key, true]))
: (options.fallbackFlags ?? {});
ok(
isObject(fallbackFlags) && isFlagValue(fallbackFlags),
"fallbackFlags must contain JSON values",
);
const flagsSyncMode =
options.flagsSyncMode ??
(options.cacheStrategy === "in-request"
Expand All @@ -240,7 +233,6 @@ export class ReflagClient {
pushUrl.searchParams.delete("channels");
this.config = {
offline,
fallbackFlags,
flagsFallbackProvider: options.flagsFallbackProvider,
fallbackContext: {
secretKeyHash: config.secretKey ? hashString(config.secretKey) : "",
Expand Down Expand Up @@ -575,10 +567,6 @@ export class ReflagClient {
if (!collection.trackSelections)
for (const [flagKey, result] of Object.entries(flags))
flags[flagKey] = localResult(flagKey, result.value);
} else {
for (const [flagKey, value] of Object.entries(this.config.fallbackFlags))
if (key === undefined || key === flagKey)
flags[flagKey] = localResult(flagKey, value);
}
const overrides = this.overrideLayers.reduce(
(current, layer) => ({ ...current, ...layer.overrides(context) }),
Expand Down
2 changes: 0 additions & 2 deletions packages/node-sdk/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,6 @@ export type ClientOptions = {
apiBaseUrl?: string;
logger?: Logger;
logLevel?: LogLevel;
/** Value-only startup fallbacks. Prefer a complete saved collection. */
fallbackFlags?: TypedFlagKey[] | FlagOverrides;
flagsFallbackProvider?: FlagsFallbackProvider;
httpClient?: HttpClient;
fetchTimeoutMs?: number;
Expand Down
3 changes: 1 addition & 2 deletions packages/node-sdk/test/bootstrap-secrecy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,6 @@ describe("bootstrap visibility boundary", () => {
async (mode) => {
const h = harness(undefined, {
offline: mode === "offline",
fallbackFlags: { fallback: privatePayload },
flagOverrides: { override: privatePayload },
...(mode === "static"
? {
Expand All @@ -223,7 +222,7 @@ describe("bootstrap visibility boundary", () => {
expect(h.client.getFlagsForBootstrap(context).flags).toEqual({});
await h.client.initialize();
expect(h.client.getFlags(context)).toMatchObject({
fallback: privatePayload,
...(mode === "static" ? { fallback: privatePayload } : {}),
override: privatePayload,
});
expect(h.client.getFlagsForBootstrap(context).flags).toEqual({});
Expand Down
1 change: 0 additions & 1 deletion packages/node-sdk/test/client-sync.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,6 @@ describe("v2 option validation", () => {
{ secretKey: 123 },
{ flagOverrides: { flag: undefined } },
{ flagOverrides: null },
{ fallbackFlags: { flag: NaN } },
{ flagsFallbackProvider: { load: () => undefined } },
{ logger: "not a logger" },
{ httpClient: false },
Expand Down
9 changes: 1 addition & 8 deletions packages/node-sdk/test/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ describe("check identity and context", () => {
it.each(["singular", "batch"])(
"records pre-initialization diagnostics at the time of a local %s read",
async (read) => {
const h = harness(graph(), { fallbackFlags: { flag: true } });
const h = harness(graph(), { flagOverrides: { flag: true } });
if (read === "singular") h.client.getFlag({}, "flag");
else h.client.getFlags({});
await h.client.initialize();
Expand Down Expand Up @@ -945,13 +945,6 @@ describe("atomic refresh and complete fallback snapshots", () => {
expect(event).not.toHaveProperty("sourceVersionId");
}
});
it("uses value-only configured fallbacks without an authored variant claim", async () => {
const h = harness({}, { fallbackFlags: { flag: false } });
await h.client.initialize();
expect(h.client.getFlag({}, "flag")).toBe(false);
await h.client.flush();
expect(h.checks()[0]).not.toHaveProperty("evalResult");
});
it("serializes fallback saves", async () => {
let finish!: () => void;
const pending = new Promise<void>((resolve) => {
Expand Down
3 changes: 1 addition & 2 deletions packages/react-native-sdk/dev/bare-rn/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ function RuntimeChecksCard() {
function FlagCard() {
const client = useClient();
const isLoading = useIsLoading();
const isEnabled = useFlag("bare-rn-demo");
const isEnabled = useFlag("bare-rn-demo", true);
const track = useTrack();

useEffect(() => {
Expand Down Expand Up @@ -177,7 +177,6 @@ export default function App() {
<ReflagProvider
publishableKey={publishableKey || "demo"}
offline={!isConfigured}
fallbackFlags={{ "bare-rn-demo": true }}
context={{
company: { id: "232" },
user: { id: "bare-rn-user", name: "Bare RN User" },
Expand Down
3 changes: 1 addition & 2 deletions packages/react-native-sdk/dev/expo/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const isConfigured = publishableKey.length > 0;
function FlagCard() {
const client = useClient();
const isLoading = useIsLoading();
const isEnabled = useFlag("expo-demo");
const isEnabled = useFlag("expo-demo", true);
const track = useTrack();

const [logs, setLogs] = useState<string[]>([]);
Expand Down Expand Up @@ -78,7 +78,6 @@ export default function App() {
<ReflagProvider
publishableKey={publishableKey || "demo"}
offline={!isConfigured}
fallbackFlags={{ "expo-demo": true }}
context={{
user: { id: "expo-user", name: "Expo User" },
other: { platform: "react-native" },
Expand Down
19 changes: 10 additions & 9 deletions packages/react-native-sdk/test/usage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -501,25 +501,26 @@ describe("React Native v2", () => {
},
);

test("offline native fallbacks and value overrides retain v2 direct-value semantics without HTTP", async () => {
test("offline reads return defaults and overrides without HTTP", async () => {
let value: unknown;
function Read() {
value = [useFlag("release"), useFlag("settings", null)];
value = [
useFlag("release", true),
useFlag("settings", { mode: "offline" }),
];
return null;
}
await mount(
<ReflagProvider
{...props}
offline
fallbackFlags={{ release: true, settings: { mode: "offline" } }}
>
<ReflagProvider {...props} offline>
<CaptureClient />
<Read />
</ReflagProvider>,
);
await settle(() => expect(value).toEqual([true, { mode: "offline" }]));
await act(async () => latestClient().setFlagOverride("settings", null));
expect(value).toEqual([true, null]);
await act(async () =>
latestClient().setFlagOverride("settings", { mode: "override" }),
);
expect(value).toEqual([true, { mode: "override" }]);
await act(async () =>
latestClient().setFlagOverride("settings", undefined),
);
Expand Down
11 changes: 5 additions & 6 deletions packages/react-native-sdk/type-tests/defaults.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,12 @@ export function NativeContracts() {
}

export const NativeOffline = (
<ReflagProvider publishableKey="synthetic" offline />
);
export const RemovedFallbacks = (
<ReflagProvider
publishableKey="synthetic"
offline
fallbackFlags={{ release: true, settings: { model: "quick" } }}
// @ts-expect-error fallbackFlags was removed; pass defaults to useFlag().
fallbackFlags={["release"]}
/>
);
// Boolean string-array shorthand remains supported by the shared v2 client.
export const BooleanOffline = (
<ReflagProvider publishableKey="synthetic" fallbackFlags={["release"]} />
);
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export const Providers = ({ publishableKey, children }: Props) => {
"optin-huddles": "true",
},
}}
fallbackFlags={["fallback-feature"]}
offline={!publishableKey}
suspense
>
Expand Down
Loading