Skip to content

Commit 49c7f52

Browse files
Merge pull request #378 from splitio/cache_expiration_move_validateCache_call
[Cache expiration] Integrate with synchronization start flow
2 parents 1b9874e + 679f841 commit 49c7f52

File tree

11 files changed

+53
-60
lines changed

11 files changed

+53
-60
lines changed

src/storages/AbstractSplitsCacheAsync.ts

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,6 @@ export abstract class AbstractSplitsCacheAsync implements ISplitsCacheAsync {
2727
return Promise.resolve(true);
2828
}
2929

30-
/**
31-
* Check if the splits information is already stored in cache.
32-
* Noop, just keeping the interface. This is used by client-side implementations only.
33-
*/
34-
checkCache(): Promise<boolean> {
35-
return Promise.resolve(false);
36-
}
37-
3830
/**
3931
* Kill `name` split and set `defaultTreatment` and `changeNumber`.
4032
* Used for SPLIT_KILL push notifications.

src/storages/AbstractSplitsCacheSync.ts

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,14 +47,6 @@ export abstract class AbstractSplitsCacheSync implements ISplitsCacheSync {
4747

4848
abstract clear(): void
4949

50-
/**
51-
* Check if the splits information is already stored in cache. This data can be preloaded.
52-
* It is used as condition to emit SDK_SPLITS_CACHE_LOADED, and then SDK_READY_FROM_CACHE.
53-
*/
54-
checkCache(): boolean {
55-
return false;
56-
}
57-
5850
/**
5951
* Kill `name` split and set `defaultTreatment` and `changeNumber`.
6052
* Used for SPLIT_KILL push notifications.

src/storages/inLocalStorage/SplitsCacheInLocal.ts

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -212,15 +212,6 @@ export class SplitsCacheInLocal extends AbstractSplitsCacheSync {
212212
}
213213
}
214214

215-
/**
216-
* Check if the splits information is already stored in browser LocalStorage.
217-
* In this function we could add more code to check if the data is valid.
218-
* @override
219-
*/
220-
checkCache(): boolean {
221-
return this.getChangeNumber() > -1;
222-
}
223-
224215
/**
225216
* Clean Splits cache if its `lastUpdated` timestamp is older than the given `expirationTimestamp`,
226217
*
@@ -245,7 +236,7 @@ export class SplitsCacheInLocal extends AbstractSplitsCacheSync {
245236
this.updateNewFilter = true;
246237

247238
// if there is cache, clear it
248-
if (this.checkCache()) this.clear();
239+
if (this.getChangeNumber() > -1) this.clear();
249240

250241
} catch (e) {
251242
this.log.error(LOG_PREFIX + e);

src/storages/inLocalStorage/__tests__/SplitsCacheInLocal.spec.ts

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,16 +30,10 @@ test('SPLIT CACHE / LocalStorage', () => {
3030
expect(cache.getSplit('lol1')).toEqual(null);
3131
expect(cache.getSplit('lol2')).toEqual(somethingElse);
3232

33-
expect(cache.checkCache()).toBe(false); // checkCache should return false until localstorage has data.
34-
3533
expect(cache.getChangeNumber() === -1).toBe(true);
3634

37-
expect(cache.checkCache()).toBe(false); // checkCache should return false until localstorage has data.
38-
3935
cache.setChangeNumber(123);
4036

41-
expect(cache.checkCache()).toBe(true); // checkCache should return true once localstorage has data.
42-
4337
expect(cache.getChangeNumber() === 123).toBe(true);
4438

4539
});

src/storages/inLocalStorage/index.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@ export function InLocalStorage(options: InLocalStorageOptions = {}): IStorageSyn
5353
telemetry: shouldRecordTelemetry(params) ? new TelemetryCacheInMemory(splits, segments) : undefined,
5454
uniqueKeys: impressionsMode === NONE ? new UniqueKeysCacheInMemoryCS() : undefined,
5555

56+
// @TODO implement
57+
validateCache() {
58+
return splits.getChangeNumber() > -1;
59+
},
60+
5661
destroy() { },
5762

5863
// When using shared instantiation with MEMORY we reuse everything but segments (they are customer per key).

src/storages/types.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -191,8 +191,6 @@ export interface ISplitsCacheBase {
191191
// only for Client-Side. Returns true if the storage is not synchronized yet (getChangeNumber() === -1) or contains a FF using segments or large segments
192192
usesSegments(): MaybeThenable<boolean>,
193193
clear(): MaybeThenable<boolean | void>,
194-
// should never reject or throw an exception. Instead return false by default, to avoid emitting SDK_READY_FROM_CACHE.
195-
checkCache(): MaybeThenable<boolean>,
196194
killLocally(name: string, defaultTreatment: string, changeNumber: number): MaybeThenable<boolean>,
197195
getNamesByFlagSets(flagSets: string[]): MaybeThenable<Set<string>[]>
198196
}
@@ -209,7 +207,6 @@ export interface ISplitsCacheSync extends ISplitsCacheBase {
209207
trafficTypeExists(trafficType: string): boolean,
210208
usesSegments(): boolean,
211209
clear(): void,
212-
checkCache(): boolean,
213210
killLocally(name: string, defaultTreatment: string, changeNumber: number): boolean,
214211
getNamesByFlagSets(flagSets: string[]): Set<string>[]
215212
}
@@ -226,7 +223,6 @@ export interface ISplitsCacheAsync extends ISplitsCacheBase {
226223
trafficTypeExists(trafficType: string): Promise<boolean>,
227224
usesSegments(): Promise<boolean>,
228225
clear(): Promise<boolean | void>,
229-
checkCache(): Promise<boolean>,
230226
killLocally(name: string, defaultTreatment: string, changeNumber: number): Promise<boolean>,
231227
getNamesByFlagSets(flagSets: string[]): Promise<Set<string>[]>
232228
}
@@ -457,6 +453,7 @@ export interface IStorageSync extends IStorageBase<
457453
IUniqueKeysCacheSync
458454
> {
459455
// Defined in client-side
456+
validateCache?: () => boolean, // @TODO support async
460457
largeSegments?: ISegmentsCacheSync,
461458
}
462459

src/sync/__tests__/syncManagerOnline.spec.ts

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { fullSettings } from '../../utils/settingsValidation/__tests__/settings.
22
import { syncTaskFactory } from './syncTask.mock';
33
import { syncManagerOnlineFactory } from '../syncManagerOnline';
44
import { IReadinessManager } from '../../readiness/types';
5+
import { SDK_SPLITS_CACHE_LOADED } from '../../readiness/constants';
56

67
jest.mock('../submitters/submitterManager', () => {
78
return {
@@ -45,8 +46,10 @@ const pushManagerFactoryMock = jest.fn(() => pushManagerMock);
4546
test('syncManagerOnline should start or not the submitter depending on user consent status', () => {
4647
const settings = { ...fullSettings };
4748

48-
// @ts-ignore
49-
const syncManager = syncManagerOnlineFactory()({ settings });
49+
const syncManager = syncManagerOnlineFactory()({
50+
settings, // @ts-ignore
51+
storage: {},
52+
});
5053
const submitterManager = syncManager.submitterManager!;
5154

5255
syncManager.start();
@@ -95,7 +98,10 @@ test('syncManagerOnline should syncAll a single time when sync is disabled', ()
9598

9699
// @ts-ignore
97100
// Test pushManager for main client
98-
const syncManager = syncManagerOnlineFactory(() => pollingManagerMock, pushManagerFactoryMock)({ settings });
101+
const syncManager = syncManagerOnlineFactory(() => pollingManagerMock, pushManagerFactoryMock)({
102+
settings, // @ts-ignore
103+
storage: { validateCache: () => false },
104+
});
99105

100106
expect(pushManagerFactoryMock).not.toBeCalled();
101107

@@ -161,7 +167,10 @@ test('syncManagerOnline should syncAll a single time when sync is disabled', ()
161167
settings.sync.enabled = true;
162168
// @ts-ignore
163169
// pushManager instantiation control test
164-
const testSyncManager = syncManagerOnlineFactory(() => pollingManagerMock, pushManagerFactoryMock)({ settings });
170+
const testSyncManager = syncManagerOnlineFactory(() => pollingManagerMock, pushManagerFactoryMock)({
171+
settings, // @ts-ignore
172+
storage: { validateCache: () => false },
173+
});
165174

166175
expect(pushManagerFactoryMock).toBeCalled();
167176

@@ -173,3 +182,18 @@ test('syncManagerOnline should syncAll a single time when sync is disabled', ()
173182
testSyncManager.stop();
174183

175184
});
185+
186+
test('syncManagerOnline should emit SDK_SPLITS_CACHE_LOADED if validateCache returns true', async () => {
187+
const params = {
188+
settings: fullSettings,
189+
storage: { validateCache: () => true },
190+
readiness: { splits: { emit: jest.fn() } }
191+
}; // @ts-ignore
192+
const syncManager = syncManagerOnlineFactory()(params);
193+
194+
await syncManager.start();
195+
196+
expect(params.readiness.splits.emit).toBeCalledWith(SDK_SPLITS_CACHE_LOADED);
197+
198+
syncManager.stop();
199+
});

src/sync/offline/syncTasks/fromObjectSyncTask.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { forOwn } from '../../../utils/lang';
22
import { IReadinessManager } from '../../../readiness/types';
3-
import { ISplitsCacheSync } from '../../../storages/types';
3+
import { IStorageSync } from '../../../storages/types';
44
import { ISplitsParser } from '../splitsParser/types';
55
import { ISplit, ISplitPartial } from '../../../dtos/types';
66
import { syncTaskFactory } from '../../syncTask';
@@ -15,7 +15,7 @@ import { SYNC_OFFLINE_DATA, ERROR_SYNC_OFFLINE_LOADING } from '../../../logger/c
1515
*/
1616
export function fromObjectUpdaterFactory(
1717
splitsParser: ISplitsParser,
18-
storage: { splits: ISplitsCacheSync },
18+
storage: Pick<IStorageSync, 'splits' | 'validateCache'>,
1919
readiness: IReadinessManager,
2020
settings: ISettings,
2121
): () => Promise<boolean> {
@@ -60,9 +60,10 @@ export function fromObjectUpdaterFactory(
6060

6161
if (startingUp) {
6262
startingUp = false;
63-
Promise.resolve(splitsCache.checkCache()).then(cacheReady => {
63+
const isCacheLoaded = storage.validateCache ? storage.validateCache() : false;
64+
Promise.resolve().then(() => {
6465
// Emits SDK_READY_FROM_CACHE
65-
if (cacheReady) readiness.splits.emit(SDK_SPLITS_CACHE_LOADED);
66+
if (isCacheLoaded) readiness.splits.emit(SDK_SPLITS_CACHE_LOADED);
6667
// Emits SDK_READY
6768
readiness.segments.emit(SDK_SEGMENTS_ARRIVED);
6869
});
@@ -80,7 +81,7 @@ export function fromObjectUpdaterFactory(
8081
*/
8182
export function fromObjectSyncTaskFactory(
8283
splitsParser: ISplitsParser,
83-
storage: { splits: ISplitsCacheSync },
84+
storage: Pick<IStorageSync, 'splits' | 'validateCache'>,
8485
readiness: IReadinessManager,
8586
settings: ISettings
8687
): ISyncTask<[], boolean> {

src/sync/polling/updaters/splitChangesUpdater.ts

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { ISplitChangesFetcher } from '../fetchers/types';
33
import { ISplit, ISplitChangesResponse, ISplitFiltersValidation } from '../../../dtos/types';
44
import { ISplitsEventEmitter } from '../../../readiness/types';
55
import { timeout } from '../../../utils/promise/timeout';
6-
import { SDK_SPLITS_ARRIVED, SDK_SPLITS_CACHE_LOADED } from '../../../readiness/constants';
6+
import { SDK_SPLITS_ARRIVED } from '../../../readiness/constants';
77
import { ILogger } from '../../../logger/types';
88
import { SYNC_SPLITS_FETCH, SYNC_SPLITS_NEW, SYNC_SPLITS_REMOVED, SYNC_SPLITS_SEGMENTS, SYNC_SPLITS_FETCH_FAILS, SYNC_SPLITS_FETCH_RETRY } from '../../../logger/constants';
99
import { startsWith } from '../../../utils/lang';
@@ -153,7 +153,7 @@ export function splitChangesUpdaterFactory(
153153
*/
154154
function _splitChangesUpdater(since: number, retry = 0): Promise<boolean> {
155155
log.debug(SYNC_SPLITS_FETCH, [since]);
156-
const fetcherPromise = Promise.resolve(splitUpdateNotification ?
156+
return Promise.resolve(splitUpdateNotification ?
157157
{ splits: [splitUpdateNotification.payload], till: splitUpdateNotification.changeNumber } :
158158
splitChangesFetcher(since, noCache, till, _promiseDecorator)
159159
)
@@ -200,15 +200,6 @@ export function splitChangesUpdaterFactory(
200200
}
201201
return false;
202202
});
203-
204-
// After triggering the requests, if we have cached splits information let's notify that to emit SDK_READY_FROM_CACHE.
205-
// Wrapping in a promise since checkCache can be async.
206-
if (splitsEventEmitter && startingUp) {
207-
Promise.resolve(splits.checkCache()).then(isCacheReady => {
208-
if (isCacheReady) splitsEventEmitter.emit(SDK_SPLITS_CACHE_LOADED);
209-
});
210-
}
211-
return fetcherPromise;
212203
}
213204

214205
let sincePromise = Promise.resolve(splits.getChangeNumber()); // `getChangeNumber` never rejects or throws error

src/sync/syncManagerOnline.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { SYNC_START_POLLING, SYNC_CONTINUE_POLLING, SYNC_STOP_POLLING } from '..
99
import { isConsentGranted } from '../consent';
1010
import { POLLING, STREAMING, SYNC_MODE_UPDATE } from '../utils/constants';
1111
import { ISdkFactoryContextSync } from '../sdkFactory/types';
12+
import { SDK_SPLITS_CACHE_LOADED } from '../readiness/constants';
1213

1314
/**
1415
* Online SyncManager factory.
@@ -28,7 +29,7 @@ export function syncManagerOnlineFactory(
2829
*/
2930
return function (params: ISdkFactoryContextSync): ISyncManagerCS {
3031

31-
const { settings, settings: { log, streamingEnabled, sync: { enabled: syncEnabled } }, telemetryTracker } = params;
32+
const { settings, settings: { log, streamingEnabled, sync: { enabled: syncEnabled } }, telemetryTracker, storage, readiness } = params;
3233

3334
/** Polling Manager */
3435
const pollingManager = pollingManagerFactory && pollingManagerFactory(params);
@@ -87,6 +88,11 @@ export function syncManagerOnlineFactory(
8788
start() {
8889
running = true;
8990

91+
if (startFirstTime) {
92+
const isCacheLoaded = storage.validateCache ? storage.validateCache() : false;
93+
if (isCacheLoaded) Promise.resolve().then(() => { readiness.splits.emit(SDK_SPLITS_CACHE_LOADED); });
94+
}
95+
9096
// start syncing splits and segments
9197
if (pollingManager) {
9298

@@ -96,7 +102,6 @@ export function syncManagerOnlineFactory(
96102
// Doesn't call `syncAll` when the syncManager is resuming
97103
if (startFirstTime) {
98104
pollingManager.syncAll();
99-
startFirstTime = false;
100105
}
101106
pushManager.start();
102107
} else {
@@ -105,13 +110,14 @@ export function syncManagerOnlineFactory(
105110
} else {
106111
if (startFirstTime) {
107112
pollingManager.syncAll();
108-
startFirstTime = false;
109113
}
110114
}
111115
}
112116

113117
// start periodic data recording (events, impressions, telemetry).
114118
submitterManager.start(!isConsentGranted(settings));
119+
120+
startFirstTime = false;
115121
},
116122

117123
/**

0 commit comments

Comments
 (0)