From 47a05a7874fdc0f0125b24277e09bbc7bb79dff5 Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Wed, 2 Dec 2026 18:54:11 +0000 Subject: [PATCH 1/3] fix(node-sdk): prevent stale fallback snapshot writes --- .changeset/ordered-fallback-snapshots.md | 7 ++ packages/node-sdk/README.md | 10 +- .../node-sdk/src/flagsFallbackProvider.ts | 113 ++++++++++++++---- .../test/flagsFallbackProvider.test.ts | 58 +++++++-- 4 files changed, 150 insertions(+), 38 deletions(-) create mode 100644 .changeset/ordered-fallback-snapshots.md diff --git a/.changeset/ordered-fallback-snapshots.md b/.changeset/ordered-fallback-snapshots.md new file mode 100644 index 00000000..2aea3fb1 --- /dev/null +++ b/.changeset/ordered-fallback-snapshots.md @@ -0,0 +1,7 @@ +--- +"@reflag/node-sdk": major +--- + +Prevent older flag snapshots from replacing newer ones in the file and Redis fallback providers. + +If you pass a custom Redis client to `fallbackProviders.redis`, it must now provide node-redis-compatible `get` and `eval` methods. The fallback provider uses `EVAL` to compare and write the snapshot atomically. Make sure the Redis user can run `EVAL`, `GET`, and `SET`. diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index 3536cc03..3b45d31d 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -300,7 +300,10 @@ await client.initialize(); The file provider stores one snapshot file per environment in the configured `directory`, using the filename -`flags-fallback-v2-.json`. +`flags-fallback-v2-.json`. Writers sharing the same file +use a sibling `.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 @@ -308,6 +311,11 @@ The built-in Redis provider creates a Redis client automatically when omitted an Without a `keyPrefix` set, it will default to the key `reflag:flags-fallback:v2:`. When you provide a custom `keyPrefix`, any trailing `:` is trimmed before `:v2:` and the hash suffix are appended. +The provider uses a Lua script to check the stored `flagStateVersion` and write in one +operation. Redis must allow `EVAL`, `GET`, and `SET` for this provider. If you supply a +custom client, it must implement node-redis-compatible `get` and `eval` methods; `get` +and `set` alone are not enough. + ```typescript import { ReflagClient, fallbackProviders } from "@reflag/node-sdk"; diff --git a/packages/node-sdk/src/flagsFallbackProvider.ts b/packages/node-sdk/src/flagsFallbackProvider.ts index 8ad3d55d..3d481127 100644 --- a/packages/node-sdk/src/flagsFallbackProvider.ts +++ b/packages/node-sdk/src/flagsFallbackProvider.ts @@ -1,5 +1,6 @@ import { promises as fs } from "fs"; import path from "path"; +import { setTimeout as delay } from "timers/promises"; import type { FlagDefinition, @@ -115,12 +116,10 @@ type GCSObjectStore = { export type RedisFallbackProviderOptions = { /** - * Optional Redis client. When omitted, a client is created using `REDIS_URL`. + * Optional Redis client with node-redis-compatible `get` and `eval` methods. + * When omitted, a client is created using `REDIS_URL`. */ - client?: { - get(key: string): Promise; - set(key: string, value: string): Promise; - }; + client?: RedisFallbackClient; /** * Prefix for generated per-environment keys. @@ -130,6 +129,33 @@ export type RedisFallbackProviderOptions = { keyPrefix?: string; }; +type RedisFallbackClient = { + get(key: string): Promise; + eval( + script: string, + options: { keys: string[]; arguments: string[] }, + ): Promise; +}; + +// 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 + 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. @@ -372,29 +398,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 }); + } }, }; } @@ -502,12 +562,10 @@ export function createRedisFallbackProvider({ keyPrefix, }: RedisFallbackProviderOptions = {}): FlagsFallbackProvider { let defaultClient: - | { - get(key: string): Promise; - set(key: string, value: string): Promise; + | (RedisFallbackClient & { connect(): Promise; isOpen: boolean; - } + }) | undefined; let connectPromise: Promise | undefined; @@ -548,10 +606,13 @@ export function createRedisFallbackProvider({ async save(context, snapshot) { const redis = await getClient(); - await redis.set( - snapshotRedisKey(context, keyPrefix), - JSON.stringify(snapshot), - ); + await redis.eval(saveRedisSnapshot, { + keys: [snapshotRedisKey(context, keyPrefix)], + arguments: [ + JSON.stringify(snapshot), + String(snapshot.flagStateVersion ?? -1), + ], + }); }, }; } diff --git a/packages/node-sdk/test/flagsFallbackProvider.test.ts b/packages/node-sdk/test/flagsFallbackProvider.test.ts index 05af5a61..ef801fc6 100644 --- a/packages/node-sdk/test/flagsFallbackProvider.test.ts +++ b/packages/node-sdk/test/flagsFallbackProvider.test.ts @@ -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"; @@ -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 }, @@ -65,7 +97,7 @@ describe("flagsFallbackProvider", () => { { ...snapshot, savedAt: "invalid" }, ])("rejects incompatible fallback envelopes %#", async (value) => { const provider = fallbackProviders.redis({ - client: { get: vi.fn(async () => JSON.stringify(value)), set: vi.fn() }, + client: { get: vi.fn(async () => JSON.stringify(value)), eval: vi.fn() }, }); await expect(provider.load(context)).resolves.toBeUndefined(); }); @@ -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, eval: vi.fn() }, + }); await expect(provider.load(context)).resolves.toEqual(snapshot); expect(get).toHaveBeenCalledWith( `reflag:flags-fallback:v2:${context.secretKeyHash.slice(0, 16)}`, @@ -190,22 +224,24 @@ describe("flagsFallbackProvider", () => { it("returns undefined for missing Redis snapshots", async () => { await expect( fallbackProviders - .redis({ client: { get: vi.fn(async () => null), set: vi.fn() } }) + .redis({ client: { get: vi.fn(async () => null), eval: vi.fn() } }) .load(context), ).resolves.toBeUndefined(); }); - it("trims Redis prefixes and saves versioned keys", async () => { - const set = vi.fn(); + it("sends a single Redis script call with the snapshot, version, and trimmed key", async () => { + const evaluate = vi.fn(); + const get = vi.fn(); await fallbackProviders .redis({ - client: { get: vi.fn(), set }, + client: { get, 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(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; From 280089b03232fd3db61b17bd1bcd607108c894a3 Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Wed, 2 Dec 2026 18:59:36 +0000 Subject: [PATCH 2/3] fix(node-sdk): preserve custom Redis fallback clients --- .changeset/ordered-fallback-snapshots.md | 6 +- packages/node-sdk/README.md | 17 +++-- .../node-sdk/src/flagsFallbackProvider.ts | 66 +++++++++++++------ .../test/flagsFallbackProvider.test.ts | 40 +++++++++-- 4 files changed, 96 insertions(+), 33 deletions(-) diff --git a/.changeset/ordered-fallback-snapshots.md b/.changeset/ordered-fallback-snapshots.md index 2aea3fb1..25902dee 100644 --- a/.changeset/ordered-fallback-snapshots.md +++ b/.changeset/ordered-fallback-snapshots.md @@ -1,7 +1,7 @@ --- -"@reflag/node-sdk": major +"@reflag/node-sdk": patch --- -Prevent older flag snapshots from replacing newer ones in the file and Redis fallback providers. +Prevent older flag snapshots from replacing newer ones in the file and built-in Redis fallback providers. -If you pass a custom Redis client to `fallbackProviders.redis`, it must now provide node-redis-compatible `get` and `eval` methods. The fallback provider uses `EVAL` to compare and write the snapshot atomically. Make sure the Redis user can run `EVAL`, `GET`, and `SET`. +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. diff --git a/packages/node-sdk/README.md b/packages/node-sdk/README.md index 3b45d31d..bedcfab0 100644 --- a/packages/node-sdk/README.md +++ b/packages/node-sdk/README.md @@ -311,10 +311,19 @@ The built-in Redis provider creates a Redis client automatically when omitted an Without a `keyPrefix` set, it will default to the key `reflag:flags-fallback:v2:`. When you provide a custom `keyPrefix`, any trailing `:` is trimmed before `:v2:` and the hash suffix are appended. -The provider uses a Lua script to check the stored `flagStateVersion` and write in one -operation. Redis must allow `EVAL`, `GET`, and `SET` for this provider. If you supply a -custom client, it must implement node-redis-compatible `get` and `eval` methods; `get` -and `set` alone are not enough. +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"; diff --git a/packages/node-sdk/src/flagsFallbackProvider.ts b/packages/node-sdk/src/flagsFallbackProvider.ts index 3d481127..c17dada2 100644 --- a/packages/node-sdk/src/flagsFallbackProvider.ts +++ b/packages/node-sdk/src/flagsFallbackProvider.ts @@ -116,11 +116,17 @@ type GCSObjectStore = { export type RedisFallbackProviderOptions = { /** - * Optional Redis client with node-redis-compatible `get` and `eval` methods. - * When omitted, a client is created using `REDIS_URL`. + * Optional Redis client. When omitted, a client is created using `REDIS_URL`. */ client?: RedisFallbackClient; + /** + * 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?: RedisEval; + /** * Prefix for generated per-environment keys. * @@ -131,12 +137,14 @@ export type RedisFallbackProviderOptions = { type RedisFallbackClient = { get(key: string): Promise; - eval( - script: string, - options: { keys: string[]; arguments: string[] }, - ): Promise; + set(key: string, value: string): Promise; }; +type RedisEval = ( + script: string, + options: { keys: string[]; arguments: string[] }, +) => Promise; + // Keep the comparison and write together on the server. An unversioned // snapshot must not replace a versioned one. const saveRedisSnapshot = ` @@ -559,21 +567,19 @@ export function createGCSFallbackProvider({ export function createRedisFallbackProvider({ client, + eval: evaluate, keyPrefix, }: RedisFallbackProviderOptions = {}): FlagsFallbackProvider { let defaultClient: | (RedisFallbackClient & { + eval: RedisEval; connect(): Promise; isOpen: boolean; }) | undefined; let connectPromise: Promise | 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", @@ -582,7 +588,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) { @@ -595,7 +601,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; @@ -605,14 +611,32 @@ export function createRedisFallbackProvider({ }, async save(context, snapshot) { - const redis = await getClient(); - await redis.eval(saveRedisSnapshot, { - keys: [snapshotRedisKey(context, keyPrefix)], - arguments: [ - JSON.stringify(snapshot), - String(snapshot.flagStateVersion ?? -1), - ], - }); + 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); + } }, }; } diff --git a/packages/node-sdk/test/flagsFallbackProvider.test.ts b/packages/node-sdk/test/flagsFallbackProvider.test.ts index ef801fc6..94fee12a 100644 --- a/packages/node-sdk/test/flagsFallbackProvider.test.ts +++ b/packages/node-sdk/test/flagsFallbackProvider.test.ts @@ -97,7 +97,7 @@ describe("flagsFallbackProvider", () => { { ...snapshot, savedAt: "invalid" }, ])("rejects incompatible fallback envelopes %#", async (value) => { const provider = fallbackProviders.redis({ - client: { get: vi.fn(async () => JSON.stringify(value)), eval: vi.fn() }, + client: { get: vi.fn(async () => JSON.stringify(value)), set: vi.fn() }, }); await expect(provider.load(context)).resolves.toBeUndefined(); }); @@ -214,7 +214,7 @@ 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, eval: vi.fn() }, + client: { get, set: vi.fn() }, }); await expect(provider.load(context)).resolves.toEqual(snapshot); expect(get).toHaveBeenCalledWith( @@ -224,20 +224,50 @@ describe("flagsFallbackProvider", () => { it("returns undefined for missing Redis snapshots", async () => { await expect( fallbackProviders - .redis({ client: { get: vi.fn(async () => null), eval: vi.fn() } }) + .redis({ client: { get: vi.fn(async () => null), set: vi.fn() } }) .load(context), ).resolves.toBeUndefined(); }); - it("sends a single Redis script call with the snapshot, version, and trimmed key", 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>().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, eval: evaluate }, + client: { get, set }, + eval: evaluate, keyPrefix: "reflag:flags-fallback:::", }) .save(context, 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"], From 7718318e64f025daef3c0173d01e2f0c269571d8 Mon Sep 17 00:00:00 2001 From: Ron Cohen Date: Thu, 3 Dec 2026 20:35:36 +0000 Subject: [PATCH 3/3] fix(node-sdk): inline Redis option types for TypeDoc --- .../node-sdk/src/flagsFallbackProvider.ts | 26 +++++++------------ 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/packages/node-sdk/src/flagsFallbackProvider.ts b/packages/node-sdk/src/flagsFallbackProvider.ts index c17dada2..6778efca 100644 --- a/packages/node-sdk/src/flagsFallbackProvider.ts +++ b/packages/node-sdk/src/flagsFallbackProvider.ts @@ -118,14 +118,20 @@ export type RedisFallbackProviderOptions = { /** * Optional Redis client. When omitted, a client is created using `REDIS_URL`. */ - client?: RedisFallbackClient; + client?: { + get(key: string): Promise; + set(key: string, value: string): Promise; + }; /** * 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?: RedisEval; + eval?: ( + script: string, + options: { keys: string[]; arguments: string[] }, + ) => Promise; /** * Prefix for generated per-environment keys. @@ -135,16 +141,6 @@ export type RedisFallbackProviderOptions = { keyPrefix?: string; }; -type RedisFallbackClient = { - get(key: string): Promise; - set(key: string, value: string): Promise; -}; - -type RedisEval = ( - script: string, - options: { keys: string[]; arguments: string[] }, -) => Promise; - // Keep the comparison and write together on the server. An unversioned // snapshot must not replace a versioned one. const saveRedisSnapshot = ` @@ -571,11 +567,7 @@ export function createRedisFallbackProvider({ keyPrefix, }: RedisFallbackProviderOptions = {}): FlagsFallbackProvider { let defaultClient: - | (RedisFallbackClient & { - eval: RedisEval; - connect(): Promise; - isOpen: boolean; - }) + | ReturnType | undefined; let connectPromise: Promise | undefined;