Skip to content
Open
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/ordered-fallback-snapshots.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@reflag/node-sdk": patch
---

Prevent older flag snapshots from replacing newer ones in the file and built-in Redis fallback providers.

The SDK-created Redis client compares and writes atomically and needs `EVAL`, `GET`, and `SET` permissions. Existing custom clients with `get` and `set` still work. Supply the `eval` option to make writes atomic with a custom client.
19 changes: 18 additions & 1 deletion packages/node-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,14 +300,31 @@ await client.initialize();

The file provider stores one snapshot file per environment in the configured
`directory`, using the filename
`flags-fallback-v2-<secretKeyHash.slice(0, 16)>.json`.
`flags-fallback-v2-<secretKeyHash.slice(0, 16)>.json`. Writers sharing the same file
use a sibling `<snapshot>.lock` directory to check the stored `flagStateVersion` before
replacing the snapshot. If a process crashes and leaves the lock behind, stop writers
before removing that directory. Readers can still load the last complete snapshot.

##### Redis provider

The built-in Redis provider creates a Redis client automatically when omitted and uses `REDIS_URL` from the environment. It stores snapshots under the configured `keyPrefix` and appends the first 16 characters of the secret key hash to that prefix.

Without a `keyPrefix` set, it will default to the key `reflag:flags-fallback:v2:<secretKeyHash.slice(0, 16)>`. When you provide a custom `keyPrefix`, any trailing `:` is trimmed before `:v2:` and the hash suffix are appended.

The SDK-created Redis client uses a Lua script to check the stored `flagStateVersion`
and write in one operation. This requires `EVAL`, `GET`, and `SET` permissions.

Custom `get`/`set` clients still work. They check the stored version before writing,
but another writer can update the key between those two commands. To make saves
atomic with a custom client, provide the `eval` option. For example, with node-redis:

```typescript
fallbackProviders.redis({
client,
eval: (script, options) => client.eval(script, options),
});
```

```typescript
import { ReflagClient, fallbackProviders } from "@reflag/node-sdk";

Expand Down
139 changes: 108 additions & 31 deletions packages/node-sdk/src/flagsFallbackProvider.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { promises as fs } from "fs";
import path from "path";
import { setTimeout as delay } from "timers/promises";

import type {
FlagDefinition,
Expand Down Expand Up @@ -122,6 +123,16 @@ export type RedisFallbackProviderOptions = {
set(key: string, value: string): Promise<unknown>;
};

/**
* Optional node-redis-compatible script executor for a supplied client.
* Without it, custom clients check the stored version with `get` before
* `set`, but cannot prevent races between writers.
*/
eval?: (
script: string,
options: { keys: string[]; arguments: string[] },
) => Promise<unknown>;

/**
* Prefix for generated per-environment keys.
*
Expand All @@ -130,6 +141,25 @@ export type RedisFallbackProviderOptions = {
keyPrefix?: string;
};

// Keep the comparison and write together on the server. An unversioned
// snapshot must not replace a versioned one.
const saveRedisSnapshot = `
local current = redis.call('GET', KEYS[1])
if current then
local ok, snapshot = pcall(cjson.decode, current)
if ok and type(snapshot) == 'table' and snapshot.version == 2 then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Validate the stored envelope before preserving its version

The Lua guard trusts any decoded object with version == 2 and a valid counter, but load() requires the full isFlagsFallbackSnapshot() envelope. For example, a stored snapshot with flagStateVersion: 100 but missing segments is rejected on load, yet this script silently refuses a valid version-99 replacement. Previously, saving repaired that value; SDK-created Redis clients and custom clients using eval now leave startup fallback unavailable until a sufficiently high version is saved or the key is cleared. Apply the stale-write guard only to envelopes accepted by the loader, and allow valid incoming snapshots to replace invalid stored values atomically.

local version = snapshot.flagStateVersion
if type(version) == 'number' and version >= 0
and version <= 9007199254740991 and version % 1 == 0
and version > tonumber(ARGV[2]) then
return 0
end
end
end
redis.call('SET', KEYS[1], ARGV[1])
return 1
`;

export type StaticFallbackProviderOptions = {
/**
* Static fallback flags keyed by flag key.
Expand Down Expand Up @@ -372,29 +402,63 @@ export function createStaticFallbackProvider({
};
}

async function loadFileSnapshot(filePath: string) {
try {
return parseSnapshot(await fs.readFile(filePath, "utf-8"));
} catch (error: any) {
if (error?.code === "ENOENT") return undefined;
throw error;
}
}

async function acquireFileLock(lockPath: string) {
for (let attempt = 0; ; attempt++) {
try {
await fs.mkdir(lockPath);
return;
} catch (error: any) {
// Do not steal a stale-looking lock: its writer may still resume.
if (error?.code !== "EEXIST" || attempt >= 100) throw error;
await delay(20);
}
}
}

export function createFileFallbackProvider({
directory,
}: FileFallbackProviderOptions = {}): FlagsFallbackProvider {
return {
async load(context) {
const resolvedPath = snapshotFilePath(context, directory);
try {
const fileContents = await fs.readFile(resolvedPath, "utf-8");
return parseSnapshot(fileContents);
} catch (error: any) {
if (error?.code === "ENOENT") {
return undefined;
}
throw error;
}
load(context) {
return loadFileSnapshot(snapshotFilePath(context, directory));
},

async save(context, snapshot) {
const resolvedPath = snapshotFilePath(context, directory);
await fs.mkdir(path.dirname(resolvedPath), { recursive: true });
const tempPath = `${resolvedPath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
await fs.writeFile(tempPath, JSON.stringify(snapshot), "utf-8");
await fs.rename(tempPath, resolvedPath);
const lockPath = `${resolvedPath}.lock`;
try {
await fs.writeFile(tempPath, JSON.stringify(snapshot), "utf-8");
await acquireFileLock(lockPath);
try {
const current = await loadFileSnapshot(resolvedPath).catch(
(error) => {
if (!(error instanceof SyntaxError)) throw error;
return undefined; // A corrupt file must not block recovery.
},
);
if (
(snapshot.flagStateVersion ?? -1) >=
(current?.flagStateVersion ?? -1)
) {
await fs.rename(tempPath, resolvedPath);
}
} finally {
await fs.rmdir(lockPath);
}
} finally {
await fs.rm(tempPath, { force: true });
}
},
};
}
Expand Down Expand Up @@ -499,23 +563,15 @@ export function createGCSFallbackProvider({

export function createRedisFallbackProvider({
client,
eval: evaluate,
keyPrefix,
}: RedisFallbackProviderOptions = {}): FlagsFallbackProvider {
let defaultClient:
| {
get(key: string): Promise<string | null | undefined>;
set(key: string, value: string): Promise<unknown>;
connect(): Promise<unknown>;
isOpen: boolean;
}
| ReturnType<typeof import("@redis/client").createClient>
| undefined;
let connectPromise: Promise<unknown> | undefined;

const getClient = async () => {
if (client) {
return client;
}

const getDefaultClient = async () => {
if (!process.env.REDIS_URL) {
throw new Error(
"fallbackProviders.redis() requires REDIS_URL to be set when no client is provided",
Expand All @@ -524,7 +580,7 @@ export function createRedisFallbackProvider({

if (!defaultClient) {
const { createClient } = await import("@redis/client");
defaultClient = createClient({ url: process.env.REDIS_URL });
defaultClient ??= createClient({ url: process.env.REDIS_URL });
}

if (!defaultClient.isOpen) {
Expand All @@ -537,7 +593,7 @@ export function createRedisFallbackProvider({

return {
async load(context) {
const redis = await getClient();
const redis = client ?? (await getDefaultClient());
const raw = await redis.get(snapshotRedisKey(context, keyPrefix));
if (!raw) {
return undefined;
Expand All @@ -547,11 +603,32 @@ export function createRedisFallbackProvider({
},

async save(context, snapshot) {
const redis = await getClient();
await redis.set(
snapshotRedisKey(context, keyPrefix),
JSON.stringify(snapshot),
);
const key = snapshotRedisKey(context, keyPrefix);
const payload = JSON.stringify(snapshot);
const version = snapshot.flagStateVersion ?? -1;

if (client && !evaluate) {
// Preserve the get/set client API. This check is best effort, not atomic.
const raw = await client.get(key);
let current: FlagsFallbackSnapshot | undefined;
try {
current = raw ? parseSnapshot(raw) : undefined;
} catch (error) {
if (!(error instanceof SyntaxError)) throw error;
}
if (version >= (current?.flagStateVersion ?? -1)) {
await client.set(key, payload);
}
return;
}

const options = { keys: [key], arguments: [payload, String(version)] };
if (client && evaluate) {
await evaluate(saveRedisSnapshot, options);
} else {
const redis = await getDefaultClient();
await redis.eval(saveRedisSnapshot, options);
}
},
};
}
82 changes: 74 additions & 8 deletions packages/node-sdk/test/flagsFallbackProvider.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mkdtemp, readFile, rm } from "fs/promises";
import { mkdtemp, readdir, readFile, rm, writeFile } from "fs/promises";
import os from "os";
import path from "path";

Expand Down Expand Up @@ -58,6 +58,38 @@ describe("flagsFallbackProvider", () => {
).toEqual(snapshot);
await expect(provider.load(context)).resolves.toEqual(snapshot);
});
it("keeps the highest file version across concurrent providers", async () => {
tempDir = await mkdtemp(path.join(os.tmpdir(), "reflag-node-sdk-"));
const options = { directory: tempDir };
await Promise.all(
Array.from({ length: 10 }, (_, i) =>
fallbackProviders.file(options).save(context, {
...snapshot,
flagStateVersion: 10 - i,
}),
),
);
const provider = fallbackProviders.file(options);
const latest = { ...snapshot, flagStateVersion: 10 };
await provider.save(context, {
...snapshot,
savedAt: "2026-03-10T00:00:00Z",
});
await provider.save(context, { ...snapshot, flagStateVersion: undefined });
await expect(provider.load(context)).resolves.toEqual(latest);

const refreshed = { ...latest, savedAt: "2026-03-10T00:00:00Z" };
await provider.save(context, refreshed);
await expect(provider.load(context)).resolves.toEqual(refreshed);
await expect(readdir(tempDir)).resolves.toEqual([filename]);
});
it("replaces a corrupt file snapshot", async () => {
tempDir = await mkdtemp(path.join(os.tmpdir(), "reflag-node-sdk-"));
await writeFile(path.join(tempDir, filename), "{broken");
const provider = fallbackProviders.file({ directory: tempDir });
await provider.save(context, snapshot);
await expect(provider.load(context)).resolves.toEqual(snapshot);
});
it.each([
{ ...snapshot, version: 1 },
{ ...snapshot, segments: undefined },
Expand Down Expand Up @@ -181,7 +213,9 @@ describe("flagsFallbackProvider", () => {
});
it("loads Redis snapshots in a versioned namespace", async () => {
const get = vi.fn(async () => JSON.stringify(snapshot));
const provider = fallbackProviders.redis({ client: { get, set: vi.fn() } });
const provider = fallbackProviders.redis({
client: { get, set: vi.fn() },
});
await expect(provider.load(context)).resolves.toEqual(snapshot);
expect(get).toHaveBeenCalledWith(
`reflag:flags-fallback:v2:${context.secretKeyHash.slice(0, 16)}`,
Expand All @@ -194,18 +228,50 @@ describe("flagsFallbackProvider", () => {
.load(context),
).resolves.toBeUndefined();
});
it("trims Redis prefixes and saves versioned keys", async () => {
it("keeps get/set-only custom Redis clients working", async () => {
const key = `reflag:flags-fallback:v2:${context.secretKeyHash.slice(0, 16)}`;
const get = vi.fn<() => Promise<string | null>>().mockResolvedValue(null);
const set = vi.fn();
const provider = fallbackProviders.redis({ client: { get, set } });
await provider.save(context, snapshot);
expect(set).toHaveBeenCalledExactlyOnceWith(key, JSON.stringify(snapshot));

get.mockResolvedValue(JSON.stringify({ ...snapshot, flagStateVersion: 2 }));
await provider.save(context, snapshot);
await provider.save(context, { ...snapshot, flagStateVersion: undefined });
expect(set).toHaveBeenCalledTimes(1);

get.mockResolvedValue("{corrupt");
await provider.save(context, snapshot);
expect(set).toHaveBeenCalledTimes(2);
});
it("does not assume a custom client's eval uses the node-redis signature", async () => {
const client = {
get: vi.fn(async () => null),
set: vi.fn(),
eval: vi.fn(),
};
await fallbackProviders.redis({ client }).save(context, snapshot);
expect(client.set).toHaveBeenCalledTimes(1);
expect(client.eval).not.toHaveBeenCalled();
});
it("uses one Redis script call when a custom client opts in", async () => {
const evaluate = vi.fn();
const get = vi.fn();
const set = vi.fn();
await fallbackProviders
.redis({
client: { get: vi.fn(), set },
client: { get, set },
eval: evaluate,
keyPrefix: "reflag:flags-fallback:::",
})
.save(context, snapshot);
expect(set).toHaveBeenCalledWith(
`reflag:flags-fallback:v2:${context.secretKeyHash.slice(0, 16)}`,
JSON.stringify(snapshot),
);
expect(get).not.toHaveBeenCalled();
expect(set).not.toHaveBeenCalled();
expect(evaluate).toHaveBeenCalledExactlyOnceWith(expect.any(String), {
keys: [`reflag:flags-fallback:v2:${context.secretKeyHash.slice(0, 16)}`],
arguments: [JSON.stringify(snapshot), "1"],
});
});
it("requires REDIS_URL when no Redis client is provided", async () => {
const previous = process.env.REDIS_URL;
Expand Down
Loading