From 98027a57b1c435040487d19b88624914a318c525 Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Wed, 7 Oct 2026 16:13:54 -0300 Subject: [PATCH 1/2] Batch flag set and counter delta write operations in the persistent storage --- CHANGES.txt | 3 + .../inLocalStorage/SplitsCacheInLocal.ts | 162 +++++++++++------- .../__tests__/SplitsCacheInLocal.spec.ts | 103 +++++++++++ 3 files changed, 208 insertions(+), 60 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index d854a85e..4c2243c1 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,3 +1,6 @@ +2.13.1 (October 8, 2026) + - Updated the 'LOCALSTORAGE' storage to batch the writes of flag sets and traffic type/segment counters when storing feature flags, reducing the time of cold initializations. + 2.13.0 (September 24, 2026) - Added support for ioredis v6 (Related to issue https://github.com/splitio/javascript-client/issues/951). Note that ioredis v6 requires Node.js 20 or above; stay on ioredis v4 or v5 for older Node.js versions. - Removed the `@types/ioredis` dependency, which is no longer required since the public type definitions don't depend on ioredis types. The `@types/node` dependency, previously installed transitively by `@types/ioredis`, is now declared explicitly, since the public type definitions use Node.js types for the `agent` and `tls` options. diff --git a/src/storages/inLocalStorage/SplitsCacheInLocal.ts b/src/storages/inLocalStorage/SplitsCacheInLocal.ts index 19154070..8687d9f9 100644 --- a/src/storages/inLocalStorage/SplitsCacheInLocal.ts +++ b/src/storages/inLocalStorage/SplitsCacheInLocal.ts @@ -8,6 +8,18 @@ import { ISettings } from '../../types'; import { setToArray } from '../../utils/lang/sets'; import { StorageAdapter } from '../types'; +/** + * Changes accumulated in memory while applying an update, so that each flag set and counter delta is written once at the end of the update. + */ +interface UpdateBatch { + flagSets: Map>; + counts: Map; +} + +function newBatch(): UpdateBatch { + return { flagSets: new Map(), counts: new Map() }; +} + export class SplitsCacheInLocal extends AbstractSplitsCacheSync { private readonly keys: KeyBuilderCS; @@ -24,41 +36,15 @@ export class SplitsCacheInLocal extends AbstractSplitsCacheSync { this.storage = storage; } - private _decrementCount(key: string) { - const count = toNumber(this.storage.getItem(key)) - 1; - if (count > 0) this.storage.setItem(key, count + ''); - else this.storage.removeItem(key); + private updateCount(batch: UpdateBatch, key: string, diff: number) { + batch.counts.set(key, (batch.counts.get(key) || 0) + diff); } - private _decrementCounts(split: ISplit) { - try { - const ttKey = this.keys.buildTrafficTypeKey(split.trafficTypeName); - this._decrementCount(ttKey); - - if (usesSegments(split)) { - const segmentsCountKey = this.keys.buildSplitsWithSegmentCountKey(); - this._decrementCount(segmentsCountKey); - } - } catch (e) { - this.log.error(LOG_PREFIX + e); - } - } - - private _incrementCounts(split: ISplit) { - try { - const ttKey = this.keys.buildTrafficTypeKey(split.trafficTypeName); - this.storage.setItem(ttKey, (toNumber(this.storage.getItem(ttKey)) + 1) + ''); - - if (usesSegments(split)) { - const segmentsCountKey = this.keys.buildSplitsWithSegmentCountKey(); - this.storage.setItem(segmentsCountKey, (toNumber(this.storage.getItem(segmentsCountKey)) + 1) + ''); - } - } catch (e) { - this.log.error(LOG_PREFIX + e); - } + private updateCounts(split: ISplit, batch: UpdateBatch, diff: number) { + this.updateCount(batch, this.keys.buildTrafficTypeKey(split.trafficTypeName), diff); + if (usesSegments(split)) this.updateCount(batch, this.keys.buildSplitsWithSegmentCountKey(), diff); } - /** * Removes all splits cache related data from localStorage (splits, counters, changeNumber and lastUpdated). * We cannot simply call `localStorage.clear()` since that implies removing user items from the storage. @@ -79,33 +65,69 @@ export class SplitsCacheInLocal extends AbstractSplitsCacheSync { this.hasSync = false; } + /** + * Overrides the default implementation to batch the flag set and counter writes: each flag set and each counter is read from + * storage once, updated in memory, and written once at the end, instead of once per feature flag. + * `update` is synchronous, so no other reader can observe the intermediate state. + */ + update(toAdd: ISplit[], toRemove: ISplit[], changeNumber: number): boolean { + const batch = newBatch(); + let updated; + try { + updated = toAdd.map(addedFF => this.addSplitToBatch(addedFF, batch)).some(result => result); + updated = toRemove.map(removedFF => this.removeSplitFromBatch(removedFF.name, batch)).some(result => result) || updated; + } finally { + this.flushBatch(batch); + } + this.setChangeNumber(changeNumber); + return updated; + } + addSplit(split: ISplit) { + const batch = newBatch(); + try { + return this.addSplitToBatch(split, batch); + } finally { + this.flushBatch(batch); + } + } + + removeSplit(name: string): boolean { + const batch = newBatch(); + try { + return this.removeSplitFromBatch(name, batch); + } finally { + this.flushBatch(batch); + } + } + + private addSplitToBatch(split: ISplit, batch: UpdateBatch) { const name = split.name; const splitKey = this.keys.buildSplitKey(name); const splitFromStorage = this.storage.getItem(splitKey); const previousSplit = splitFromStorage ? JSON.parse(splitFromStorage) : null; if (previousSplit) { - this._decrementCounts(previousSplit); - this.removeFromFlagSets(previousSplit.name, previousSplit.sets); + this.updateCounts(previousSplit, batch, -1); + this.removeFromFlagSets(previousSplit.name, previousSplit.sets, batch); } this.storage.setItem(splitKey, JSON.stringify(split)); - this._incrementCounts(split); - this.addToFlagSets(split); + this.updateCounts(split, batch, 1); + this.addToFlagSets(split, batch); return true; } - removeSplit(name: string): boolean { + private removeSplitFromBatch(name: string, batch: UpdateBatch): boolean { const split = this.getSplit(name); if (!split) return false; this.storage.removeItem(this.keys.buildSplitKey(name)); - this._decrementCounts(split); - this.removeFromFlagSets(split.name, split.sets); + this.updateCounts(split, batch, -1); + this.removeFromFlagSets(split.name, split.sets, batch); return true; } @@ -184,7 +206,7 @@ export class SplitsCacheInLocal extends AbstractSplitsCacheSync { }); } - private addToFlagSets(featureFlag: ISplit) { + private addToFlagSets(featureFlag: ISplit, batch: UpdateBatch) { if (!featureFlag.sets) return; featureFlag.sets.forEach(featureFlagSet => { @@ -193,42 +215,62 @@ export class SplitsCacheInLocal extends AbstractSplitsCacheSync { const flagSetKey = this.keys.buildFlagSetKey(featureFlagSet); - const flagSetFromStorage = this.storage.getItem(flagSetKey); - - const flagSetCache = new Set(flagSetFromStorage ? JSON.parse(flagSetFromStorage) : []); - - if (flagSetCache.has(featureFlag.name)) return; - - flagSetCache.add(featureFlag.name); - - this.storage.setItem(flagSetKey, JSON.stringify(setToArray(flagSetCache))); + this.getFlagSetFromBatch(flagSetKey, batch).add(featureFlag.name); }); } - private removeFromFlagSets(featureFlagName: string, flagSets?: string[] | null) { + private removeFromFlagSets(featureFlagName: string, flagSets: string[] | null | undefined, batch: UpdateBatch) { if (!flagSets) return; flagSets.forEach(flagSet => { - this.removeNames(flagSet, featureFlagName); + this.removeNames(flagSet, featureFlagName, batch); }); } - private removeNames(flagSetName: string, featureFlagName: string) { + private removeNames(flagSetName: string, featureFlagName: string, batch: UpdateBatch) { const flagSetKey = this.keys.buildFlagSetKey(flagSetName); - const flagSetFromStorage = this.storage.getItem(flagSetKey); - - if (!flagSetFromStorage) return; + // nothing to remove from a flag set that is neither in storage nor in the batch + if (!batch.flagSets.has(flagSetKey) && !this.storage.getItem(flagSetKey)) return; - const flagSetCache = new Set(JSON.parse(flagSetFromStorage)); - flagSetCache.delete(featureFlagName); + this.getFlagSetFromBatch(flagSetKey, batch).delete(featureFlagName); + } - if (flagSetCache.size === 0) { - this.storage.removeItem(flagSetKey); - return; + /** + * Returns the flag names of the given flag set, reading from storage only the first time + */ + private getFlagSetFromBatch(flagSetKey: string, batch: UpdateBatch): Set { + let flagSetCache = batch.flagSets.get(flagSetKey); + if (!flagSetCache) { + const flagSetFromStorage = this.storage.getItem(flagSetKey); + flagSetCache = new Set(flagSetFromStorage ? JSON.parse(flagSetFromStorage) : []); + batch.flagSets.set(flagSetKey, flagSetCache); } + return flagSetCache; + } + + private flushBatch(batch: UpdateBatch) { + // flush counts + batch.counts.forEach((diff, key) => { + try { + if (diff === 0) return; + const count = toNumber(this.storage.getItem(key)) + diff; + if (count > 0) this.storage.setItem(key, count + ''); + else this.storage.removeItem(key); + } catch (e) { + this.log.error(LOG_PREFIX + e); + } + }); - this.storage.setItem(flagSetKey, JSON.stringify(setToArray(flagSetCache))); + // flush flag sets + batch.flagSets.forEach((flagSetCache, flagSetKey) => { + try { + if (flagSetCache.size === 0) this.storage.removeItem(flagSetKey); + else this.storage.setItem(flagSetKey, JSON.stringify(setToArray(flagSetCache))); + } catch (e) { + this.log.error(LOG_PREFIX + e); + } + }); } } diff --git a/src/storages/inLocalStorage/__tests__/SplitsCacheInLocal.spec.ts b/src/storages/inLocalStorage/__tests__/SplitsCacheInLocal.spec.ts index 976baa72..0f04d29f 100644 --- a/src/storages/inLocalStorage/__tests__/SplitsCacheInLocal.spec.ts +++ b/src/storages/inLocalStorage/__tests__/SplitsCacheInLocal.spec.ts @@ -3,8 +3,17 @@ import { KeyBuilderCS } from '../../KeyBuilderCS'; import { splitWithUserTT, splitWithAccountTT, splitWithAccountTTAndUsesSegments, something, somethingElse, featureFlagOne, featureFlagTwo, featureFlagThree, featureFlagWithEmptyFS, featureFlagWithoutFS } from '../../__tests__/testUtils'; import { ISplit } from '../../../dtos/types'; import { fullSettings } from '../../../utils/settingsValidation/__tests__/settings.mocks'; +import { StorageAdapter } from '../../types'; import { storages, PREFIX } from './wrapper.mock'; +function storageMethods(storage: StorageAdapter) { + return { + get length() { return storage.length; }, + key: (index: number) => storage.key(index), + getItem: (key: string) => storage.getItem(key), + removeItem: (key: string) => storage.removeItem(key), + }; +} describe.each(storages)('SPLITS CACHE', (storage) => { test('LocalStorage', () => { @@ -230,4 +239,98 @@ describe.each(storages)('SPLITS CACHE', (storage) => { cache.clear(); expect(storage.length).toBe(0); }); + + test('LocalStorage / flag sets are batched in update', () => { + const keys = new KeyBuilderCS(PREFIX, 'user'); + const writes: string[] = []; + const spiedStorage = { ...storageMethods(storage), setItem: (key: string, value: string) => { writes.push(key); storage.setItem(key, value); } }; + const cache = new SplitsCacheInLocal(fullSettings, keys, spiedStorage); + cache.clear(); + const ff = (name: string, sets: string[]) => ({ ...featureFlagOne, name, sets } as ISplit); + + // several flags across overlapping sets + cache.update([ff('a', ['x', 'y']), ff('b', ['y', 'z']), ff('c', ['x', 'y', 'z'])], [], 1); + expect(cache.getNamesByFlagSets(['x', 'y', 'z'])).toEqual([new Set(['a', 'c']), new Set(['a', 'b', 'c']), new Set(['b', 'c'])]); + + // each flag set is serialized once per update + writes.length = 0; + cache.update([ff('d', ['x', 'y']), ff('e', ['x', 'y'])], [], 2); + const writesPerSet = (set: string) => writes.filter(key => key === keys.buildFlagSetKey(set)).length; + expect(writesPerSet('x')).toBe(1); + expect(writesPerSet('y')).toBe(1); + + // a flag changing sets, a flag removed, and an empty set being removed + cache.update([ff('a', ['z'])], [ff('b', [])], 3); + expect(cache.getNamesByFlagSets(['x', 'y', 'z'])).toEqual([new Set(['c', 'd', 'e']), new Set(['c', 'd', 'e']), new Set(['a', 'c'])]); + + cache.update([ff('a', ['w'])], [], 4); + expect(cache.getNamesByFlagSets(['w', 'z'])).toEqual([new Set(['a']), new Set(['c'])]); + + cache.update([], [ff('a', [])], 5); + expect(cache.getNamesByFlagSets(['w'])).toEqual([new Set()]); + expect(storage.getItem(keys.buildFlagSetKey('w'))).toBeNull(); + + // flag added and then moved within the same update + cache.update([ff('f', ['p']), ff('f', ['q'])], [], 6); + expect(cache.getNamesByFlagSets(['p', 'q'])).toEqual([new Set(), new Set(['f'])]); + expect(storage.getItem(keys.buildFlagSetKey('p'))).toBeNull(); + + cache.clear(); + }); + + test('LocalStorage / traffic type and segments counts are batched in update', () => { + const keys = new KeyBuilderCS(PREFIX, 'user'); + const writes: string[] = []; + const spiedStorage = { ...storageMethods(storage), setItem: (key: string, value: string) => { writes.push(key); storage.setItem(key, value); } }; + const cache = new SplitsCacheInLocal(fullSettings, keys, spiedStorage); + cache.clear(); + + const ttKey = (tt: string) => keys.buildTrafficTypeKey(tt); + const segmentsKey = keys.buildSplitsWithSegmentCountKey(); + const writesOf = (key: string) => writes.filter(k => k === key).length; + + cache.update([splitWithUserTT, splitWithAccountTT, splitWithAccountTTAndUsesSegments], [], 1); + expect(storage.getItem(ttKey('user_tt'))).toBe('1'); + expect(storage.getItem(ttKey('account_tt'))).toBe('2'); + expect(storage.getItem(segmentsKey)).toBe('1'); + + const many = (n: number, tt: string, withSegments: boolean) => Array.from({ length: n }, (_, i) => ({ + ...(withSegments ? splitWithAccountTTAndUsesSegments : splitWithUserTT), name: `${tt}_${withSegments}_${i}`, trafficTypeName: tt + } as ISplit)); + + writes.length = 0; + cache.update([...many(5, 'user_tt', false), ...many(3, 'account_tt', true)], [], 2); + expect(writesOf(ttKey('user_tt'))).toBe(1); + expect(writesOf(ttKey('account_tt'))).toBe(1); + expect(writesOf(segmentsKey)).toBe(1); + expect(storage.getItem(ttKey('user_tt'))).toBe('6'); + expect(storage.getItem(ttKey('account_tt'))).toBe('5'); + expect(storage.getItem(segmentsKey)).toBe('4'); + + // a flag changing traffic type and no longer using segments, and removing flags down to zero + cache.update([{ ...splitWithAccountTTAndUsesSegments, trafficTypeName: 'user_tt', conditions: [] } as ISplit], many(5, 'user_tt', false), 3); + expect(storage.getItem(ttKey('user_tt'))).toBe('2'); + expect(storage.getItem(ttKey('account_tt'))).toBe('4'); + expect(storage.getItem(segmentsKey)).toBe('3'); + expect(cache.trafficTypeExists('user_tt')).toBe(true); + + cache.update([], [...many(3, 'account_tt', true), splitWithAccountTT, splitWithAccountTTAndUsesSegments], 4); + expect(storage.getItem(ttKey('account_tt'))).toBeNull(); + expect(storage.getItem(segmentsKey)).toBeNull(); + + cache.clear(); + }); + + test('LocalStorage / flag sets flush errors are logged and do not throw', () => { + const failingStorage = { ...storageMethods(storage), setItem: (key: string, value: string) => { if (key.indexOf('.flagSet.') > -1) throw new Error('quota'); storage.setItem(key, value); } }; + const cache = new SplitsCacheInLocal(fullSettings, new KeyBuilderCS(PREFIX, 'user'), failingStorage); + cache.clear(); + const errorSpy = jest.spyOn(fullSettings.log, 'error'); + + expect(() => cache.update([featureFlagOne], [], 1)).not.toThrow(); + expect(errorSpy).toHaveBeenCalled(); + + errorSpy.mockRestore(); + cache.clear(); + }); }); From 052f65929836283e598f6fb82c7b48728a5b7c6e Mon Sep 17 00:00:00 2001 From: Emiliano Sanchez Date: Wed, 7 Oct 2026 17:35:16 -0300 Subject: [PATCH 2/2] prepare release --- CHANGES.txt | 2 +- package-lock.json | 9 +++++---- package.json | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index 4c2243c1..204118b7 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,4 +1,4 @@ -2.13.1 (October 8, 2026) +2.13.1 (October 7, 2026) - Updated the 'LOCALSTORAGE' storage to batch the writes of flag sets and traffic type/segment counters when storing feature flags, reducing the time of cold initializations. 2.13.0 (September 24, 2026) diff --git a/package-lock.json b/package-lock.json index 2340954a..db75dea5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@splitsoftware/splitio-commons", - "version": "2.13.0", + "version": "2.13.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@splitsoftware/splitio-commons", - "version": "2.13.0", + "version": "2.13.1", "license": "Apache-2.0", "dependencies": { "@types/node": ">=14.0.0", @@ -7337,8 +7337,9 @@ "node_modules/sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", - "dev": true + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", + "dev": true, + "license": "BSD-3-Clause" }, "node_modules/stack-utils": { "version": "2.0.6", diff --git a/package.json b/package.json index a35ab55b..6db1398e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@splitsoftware/splitio-commons", - "version": "2.13.0", + "version": "2.13.1", "description": "Split JavaScript SDK common components", "main": "cjs/index.js", "module": "esm/index.js",