@splitsoftware/splitio-commons 1.17.1-rc.2 → 1.17.1-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGES.txt +4 -3
  2. package/cjs/readiness/readinessManager.js +13 -2
  3. package/cjs/sdkClient/sdkClientMethodCS.js +0 -1
  4. package/cjs/sdkClient/sdkClientMethodCSWithTT.js +0 -1
  5. package/cjs/sdkFactory/index.js +27 -11
  6. package/cjs/storages/{AbstractSegmentsCacheSync.js → AbstractMySegmentsCacheSync.js} +15 -17
  7. package/cjs/storages/AbstractSplitsCacheAsync.js +7 -0
  8. package/cjs/storages/AbstractSplitsCacheSync.js +7 -0
  9. package/cjs/storages/dataLoader.js +32 -65
  10. package/cjs/storages/inLocalStorage/MySegmentsCacheInLocal.js +5 -5
  11. package/cjs/storages/inLocalStorage/SplitsCacheInLocal.js +9 -1
  12. package/cjs/storages/inLocalStorage/index.js +1 -4
  13. package/cjs/storages/inMemory/InMemoryStorageCS.js +5 -17
  14. package/cjs/storages/inMemory/MySegmentsCacheInMemory.js +5 -5
  15. package/cjs/storages/inMemory/SegmentsCacheInMemory.js +13 -27
  16. package/cjs/storages/inMemory/SplitsCacheInMemory.js +0 -1
  17. package/cjs/storages/inRedis/SegmentsCacheInRedis.js +13 -19
  18. package/cjs/storages/pluggable/SegmentsCachePluggable.js +11 -32
  19. package/cjs/sync/offline/syncManagerOffline.js +18 -11
  20. package/cjs/sync/offline/syncTasks/fromObjectSyncTask.js +7 -2
  21. package/cjs/sync/polling/pollingManagerSS.js +3 -3
  22. package/cjs/sync/polling/updaters/segmentChangesUpdater.js +12 -28
  23. package/cjs/sync/polling/updaters/splitChangesUpdater.js +10 -1
  24. package/cjs/sync/syncManagerOnline.js +20 -21
  25. package/cjs/trackers/eventTracker.js +12 -10
  26. package/cjs/trackers/impressionsTracker.js +16 -14
  27. package/cjs/trackers/uniqueKeysTracker.js +5 -3
  28. package/cjs/utils/settingsValidation/storage/storageCS.js +12 -1
  29. package/esm/readiness/readinessManager.js +13 -2
  30. package/esm/sdkClient/sdkClientMethodCS.js +0 -1
  31. package/esm/sdkClient/sdkClientMethodCSWithTT.js +0 -1
  32. package/esm/sdkFactory/index.js +28 -12
  33. package/esm/storages/{AbstractSegmentsCacheSync.js → AbstractMySegmentsCacheSync.js} +14 -16
  34. package/esm/storages/AbstractSplitsCacheAsync.js +7 -0
  35. package/esm/storages/AbstractSplitsCacheSync.js +7 -0
  36. package/esm/storages/dataLoader.js +30 -62
  37. package/esm/storages/inLocalStorage/MySegmentsCacheInLocal.js +5 -5
  38. package/esm/storages/inLocalStorage/SplitsCacheInLocal.js +9 -1
  39. package/esm/storages/inLocalStorage/index.js +2 -5
  40. package/esm/storages/inMemory/InMemoryStorageCS.js +5 -17
  41. package/esm/storages/inMemory/MySegmentsCacheInMemory.js +5 -5
  42. package/esm/storages/inMemory/SegmentsCacheInMemory.js +13 -27
  43. package/esm/storages/inMemory/SplitsCacheInMemory.js +0 -1
  44. package/esm/storages/inRedis/SegmentsCacheInRedis.js +13 -19
  45. package/esm/storages/pluggable/SegmentsCachePluggable.js +11 -32
  46. package/esm/sync/offline/syncManagerOffline.js +18 -11
  47. package/esm/sync/offline/syncTasks/fromObjectSyncTask.js +8 -3
  48. package/esm/sync/polling/pollingManagerSS.js +3 -3
  49. package/esm/sync/polling/updaters/segmentChangesUpdater.js +12 -28
  50. package/esm/sync/polling/updaters/splitChangesUpdater.js +11 -2
  51. package/esm/sync/syncManagerOnline.js +20 -21
  52. package/esm/trackers/eventTracker.js +12 -10
  53. package/esm/trackers/impressionsTracker.js +16 -14
  54. package/esm/trackers/uniqueKeysTracker.js +5 -3
  55. package/esm/utils/settingsValidation/storage/storageCS.js +10 -0
  56. package/package.json +1 -1
  57. package/src/readiness/readinessManager.ts +12 -3
  58. package/src/readiness/types.ts +3 -0
  59. package/src/sdkClient/sdkClientMethodCS.ts +0 -2
  60. package/src/sdkClient/sdkClientMethodCSWithTT.ts +0 -2
  61. package/src/sdkFactory/index.ts +30 -14
  62. package/src/sdkFactory/types.ts +2 -0
  63. package/src/storages/{AbstractSegmentsCacheSync.ts → AbstractMySegmentsCacheSync.ts} +13 -28
  64. package/src/storages/AbstractSplitsCacheAsync.ts +8 -0
  65. package/src/storages/AbstractSplitsCacheSync.ts +8 -0
  66. package/src/storages/dataLoader.ts +32 -63
  67. package/src/storages/inLocalStorage/MySegmentsCacheInLocal.ts +5 -5
  68. package/src/storages/inLocalStorage/SplitsCacheInLocal.ts +10 -1
  69. package/src/storages/inLocalStorage/index.ts +2 -6
  70. package/src/storages/inMemory/InMemoryStorageCS.ts +5 -20
  71. package/src/storages/inMemory/MySegmentsCacheInMemory.ts +5 -5
  72. package/src/storages/inMemory/SegmentsCacheInMemory.ts +12 -26
  73. package/src/storages/inMemory/SplitsCacheInMemory.ts +0 -1
  74. package/src/storages/inRedis/SegmentsCacheInRedis.ts +13 -22
  75. package/src/storages/pluggable/SegmentsCachePluggable.ts +11 -35
  76. package/src/storages/types.ts +9 -10
  77. package/src/sync/offline/syncManagerOffline.ts +21 -13
  78. package/src/sync/offline/syncTasks/fromObjectSyncTask.ts +7 -3
  79. package/src/sync/polling/pollingManagerSS.ts +2 -3
  80. package/src/sync/polling/updaters/segmentChangesUpdater.ts +13 -29
  81. package/src/sync/polling/updaters/splitChangesUpdater.ts +11 -3
  82. package/src/sync/syncManagerOnline.ts +17 -17
  83. package/src/sync/types.ts +1 -1
  84. package/src/trackers/eventTracker.ts +11 -8
  85. package/src/trackers/impressionsTracker.ts +13 -10
  86. package/src/trackers/types.ts +1 -0
  87. package/src/trackers/uniqueKeysTracker.ts +6 -4
  88. package/src/types.ts +8 -9
  89. package/src/utils/settingsValidation/storage/storageCS.ts +13 -0
  90. package/types/readiness/types.d.ts +3 -0
  91. package/types/sdkFactory/types.d.ts +1 -0
  92. package/types/storages/AbstractSplitsCacheAsync.d.ts +5 -0
  93. package/types/storages/AbstractSplitsCacheSync.d.ts +5 -0
  94. package/types/storages/dataLoader.d.ts +6 -17
  95. package/types/storages/inLocalStorage/MySegmentsCacheInLocal.d.ts +5 -5
  96. package/types/storages/inLocalStorage/SplitsCacheInLocal.d.ts +6 -0
  97. package/types/storages/inMemory/MySegmentsCacheInMemory.d.ts +5 -5
  98. package/types/storages/inMemory/SegmentsCacheInMemory.d.ts +5 -7
  99. package/types/storages/inMemory/SplitsCacheInMemory.d.ts +0 -1
  100. package/types/storages/inRedis/SegmentsCacheInRedis.d.ts +6 -3
  101. package/types/storages/pluggable/SegmentsCachePluggable.d.ts +4 -16
  102. package/types/storages/types.d.ts +7 -10
  103. package/types/sync/types.d.ts +1 -1
  104. package/types/trackers/eventTracker.d.ts +1 -1
  105. package/types/trackers/impressionsTracker.d.ts +1 -1
  106. package/types/trackers/types.d.ts +1 -0
  107. package/types/types.d.ts +8 -8
  108. package/types/utils/settingsValidation/storage/storageCS.d.ts +5 -0
@@ -7,7 +7,7 @@ import { syncTaskFactory } from '../../syncTask';
7
7
  import { ISyncTask } from '../../types';
8
8
  import { ISettings } from '../../../types';
9
9
  import { CONTROL } from '../../../utils/constants';
10
- import { SDK_SPLITS_ARRIVED, SDK_SEGMENTS_ARRIVED } from '../../../readiness/constants';
10
+ import { SDK_SPLITS_ARRIVED, SDK_SEGMENTS_ARRIVED, SDK_SPLITS_CACHE_LOADED } from '../../../readiness/constants';
11
11
  import { SYNC_OFFLINE_DATA, ERROR_SYNC_OFFLINE_LOADING } from '../../../logger/constants';
12
12
 
13
13
  /**
@@ -60,8 +60,12 @@ export function fromObjectUpdaterFactory(
60
60
 
61
61
  if (startingUp) {
62
62
  startingUp = false;
63
- // Emits SDK_READY
64
- readiness.segments.emit(SDK_SEGMENTS_ARRIVED);
63
+ Promise.resolve(splitsCache.checkCache()).then(cacheReady => {
64
+ // Emits SDK_READY_FROM_CACHE
65
+ if (cacheReady) readiness.splits.emit(SDK_SPLITS_CACHE_LOADED);
66
+ // Emits SDK_READY
67
+ readiness.segments.emit(SDK_SEGMENTS_ARRIVED);
68
+ });
65
69
  }
66
70
  return true;
67
71
  });
@@ -1,7 +1,6 @@
1
1
  import { splitsSyncTaskFactory } from './syncTasks/splitsSyncTask';
2
2
  import { segmentsSyncTaskFactory } from './syncTasks/segmentsSyncTask';
3
3
  import { IPollingManager, ISegmentsSyncTask, ISplitsSyncTask } from './types';
4
- import { thenable } from '../../utils/promise/thenable';
5
4
  import { POLLING_START, POLLING_STOP, LOG_PREFIX_SYNC_POLLING } from '../../logger/constants';
6
5
  import { ISdkFactoryContextSync } from '../../sdkFactory/types';
7
6
 
@@ -29,9 +28,9 @@ export function pollingManagerSSFactory(
29
28
  log.debug(LOG_PREFIX_SYNC_POLLING + `Segments will be refreshed each ${settings.scheduler.segmentsRefreshRate} millis`);
30
29
 
31
30
  const startingUp = splitsSyncTask.start();
32
- if (thenable(startingUp)) {
31
+ if (startingUp) {
33
32
  startingUp.then(() => {
34
- segmentsSyncTask.start();
33
+ if (splitsSyncTask.isRunning()) segmentsSyncTask.start();
35
34
  });
36
35
  }
37
36
  },
@@ -1,12 +1,9 @@
1
1
  import { ISegmentChangesFetcher } from '../fetchers/types';
2
2
  import { ISegmentsCacheBase } from '../../../storages/types';
3
3
  import { IReadinessManager } from '../../../readiness/types';
4
- import { MaybeThenable } from '../../../dtos/types';
5
- import { findIndex } from '../../../utils/lang';
6
4
  import { SDK_SEGMENTS_ARRIVED } from '../../../readiness/constants';
7
5
  import { ILogger } from '../../../logger/types';
8
6
  import { LOG_PREFIX_INSTANTIATION, LOG_PREFIX_SYNC_SEGMENTS } from '../../../logger/constants';
9
- import { thenable } from '../../../utils/promise/thenable';
10
7
 
11
8
  type ISegmentChangesUpdater = (fetchOnlyNew?: boolean, segmentName?: string, noCache?: boolean, till?: number) => Promise<boolean>
12
9
 
@@ -30,31 +27,22 @@ export function segmentChangesUpdaterFactory(
30
27
 
31
28
  let readyOnAlreadyExistentState = true;
32
29
 
33
- function updateSegment(segmentName: string, noCache?: boolean, till?: number, fetchOnlyNew?: boolean) {
30
+ function updateSegment(segmentName: string, noCache?: boolean, till?: number, fetchOnlyNew?: boolean): Promise<boolean> {
34
31
  log.debug(`${LOG_PREFIX_SYNC_SEGMENTS}Processing segment ${segmentName}`);
35
32
  let sincePromise = Promise.resolve(segments.getChangeNumber(segmentName));
36
33
 
37
34
  return sincePromise.then(since => {
38
35
  // if fetchOnlyNew flag, avoid processing already fetched segments
39
- if (fetchOnlyNew && since !== -1) return -1;
40
-
41
- return segmentChangesFetcher(since, segmentName, noCache, till).then(function (changes) {
42
- let changeNumber = -1;
43
- const results: MaybeThenable<boolean | void>[] = [];
44
- changes.forEach(x => {
45
- if (x.added.length > 0) results.push(segments.addToSegment(segmentName, x.added));
46
- if (x.removed.length > 0) results.push(segments.removeFromSegment(segmentName, x.removed));
47
- if (x.added.length > 0 || x.removed.length > 0) {
48
- results.push(segments.setChangeNumber(segmentName, x.till));
49
- changeNumber = x.till;
50
- }
51
-
52
- log.debug(`${LOG_PREFIX_SYNC_SEGMENTS}Processed ${segmentName} with till = ${x.till}. Added: ${x.added.length}. Removed: ${x.removed.length}`);
36
+ return fetchOnlyNew && since !== -1 ?
37
+ false :
38
+ segmentChangesFetcher(since, segmentName, noCache, till).then((changes) => {
39
+ return Promise.all(changes.map(x => {
40
+ log.debug(`${LOG_PREFIX_SYNC_SEGMENTS}Processing ${segmentName} with till = ${x.till}. Added: ${x.added.length}. Removed: ${x.removed.length}`);
41
+ return segments.update(x.name, x.added, x.removed, x.till);
42
+ })).then((updates) => {
43
+ return updates.some(update => update);
44
+ });
53
45
  });
54
- // If at least one storage operation result is a promise, join all in a single promise.
55
- if (results.some(result => thenable(result))) return Promise.all(results).then(() => changeNumber);
56
- return changeNumber;
57
- });
58
46
  });
59
47
  }
60
48
  /**
@@ -75,16 +63,12 @@ export function segmentChangesUpdaterFactory(
75
63
  let segmentsPromise = Promise.resolve(segmentName ? [segmentName] : segments.getRegisteredSegments());
76
64
 
77
65
  return segmentsPromise.then(segmentNames => {
78
- // Async fetchers are collected here.
79
- const updaters: Promise<number>[] = [];
80
-
81
- for (let index = 0; index < segmentNames.length; index++) {
82
- updaters.push(updateSegment(segmentNames[index], noCache, till, fetchOnlyNew));
83
- }
66
+ // Async fetchers
67
+ const updaters = segmentNames.map(segmentName => updateSegment(segmentName, noCache, till, fetchOnlyNew));
84
68
 
85
69
  return Promise.all(updaters).then(shouldUpdateFlags => {
86
70
  // if at least one segment fetch succeeded, mark segments ready
87
- if (findIndex(shouldUpdateFlags, v => v !== -1) !== -1 || readyOnAlreadyExistentState) {
71
+ if (shouldUpdateFlags.some(update => update) || readyOnAlreadyExistentState) {
88
72
  readyOnAlreadyExistentState = false;
89
73
  if (readiness) readiness.segments.emit(SDK_SEGMENTS_ARRIVED);
90
74
  }
@@ -4,7 +4,7 @@ import { ISplitChangesFetcher } from '../fetchers/types';
4
4
  import { ISplit, ISplitChangesResponse, ISplitFiltersValidation } from '../../../dtos/types';
5
5
  import { ISplitsEventEmitter } from '../../../readiness/types';
6
6
  import { timeout } from '../../../utils/promise/timeout';
7
- import { SDK_SPLITS_ARRIVED } from '../../../readiness/constants';
7
+ import { SDK_SPLITS_ARRIVED, SDK_SPLITS_CACHE_LOADED } from '../../../readiness/constants';
8
8
  import { ILogger } from '../../../logger/types';
9
9
  import { SYNC_SPLITS_FETCH, SYNC_SPLITS_NEW, SYNC_SPLITS_REMOVED, SYNC_SPLITS_SEGMENTS, SYNC_SPLITS_FETCH_FAILS, SYNC_SPLITS_FETCH_RETRY } from '../../../logger/constants';
10
10
  import { startsWith } from '../../../utils/lang';
@@ -153,8 +153,7 @@ export function splitChangesUpdaterFactory(
153
153
  */
154
154
  function _splitChangesUpdater(since: number, retry = 0): Promise<boolean> {
155
155
  log.debug(SYNC_SPLITS_FETCH, [since]);
156
-
157
- return Promise.resolve(splitUpdateNotification ?
156
+ const fetcherPromise = Promise.resolve(splitUpdateNotification ?
158
157
  { splits: [splitUpdateNotification.payload], till: splitUpdateNotification.changeNumber } :
159
158
  splitChangesFetcher(since, noCache, till, _promiseDecorator)
160
159
  )
@@ -201,6 +200,15 @@ export function splitChangesUpdaterFactory(
201
200
  }
202
201
  return false;
203
202
  });
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;
204
212
  }
205
213
 
206
214
  let sincePromise = Promise.resolve(splits.getChangeNumber()); // `getChangeNumber` never rejects or throws error
@@ -143,27 +143,27 @@ export function syncManagerOnlineFactory(
143
143
 
144
144
  const mySegmentsSyncTask = (pollingManager as IPollingManagerCS).add(matchingKey, readinessManager, storage);
145
145
 
146
- return {
147
- isRunning: mySegmentsSyncTask.isRunning,
148
- start() {
149
- if (syncEnabled) {
150
- if (pushManager) {
151
- if (pollingManager!.isRunning()) {
152
- // if doing polling, we must start the periodic fetch of data
153
- if (storage.splits.usesSegments()) mySegmentsSyncTask.start();
154
- } else {
155
- // if not polling, we must execute the sync task for the initial fetch
156
- // of segments since `syncAll` was already executed when starting the main client
157
- mySegmentsSyncTask.execute();
158
- }
159
- pushManager.add(matchingKey, mySegmentsSyncTask);
160
- } else {
146
+ if (running) {
147
+ if (syncEnabled) {
148
+ if (pushManager) {
149
+ if (pollingManager!.isRunning()) {
150
+ // if doing polling, we must start the periodic fetch of data
161
151
  if (storage.splits.usesSegments()) mySegmentsSyncTask.start();
152
+ } else {
153
+ // if not polling, we must execute the sync task for the initial fetch
154
+ // of segments since `syncAll` was already executed when starting the main client
155
+ mySegmentsSyncTask.execute();
162
156
  }
157
+ pushManager.add(matchingKey, mySegmentsSyncTask);
163
158
  } else {
164
- if (!readinessManager.isReady()) mySegmentsSyncTask.execute();
159
+ if (storage.splits.usesSegments()) mySegmentsSyncTask.start();
165
160
  }
166
- },
161
+ } else {
162
+ if (!readinessManager.isReady()) mySegmentsSyncTask.execute();
163
+ }
164
+ }
165
+
166
+ return {
167
167
  stop() {
168
168
  // check in case `client.destroy()` has been invoked more than once for the same client
169
169
  const mySegmentsSyncTask = (pollingManager as IPollingManagerCS).get(matchingKey);
package/src/sync/types.ts CHANGED
@@ -44,5 +44,5 @@ export interface ISyncManager extends ITask {
44
44
  }
45
45
 
46
46
  export interface ISyncManagerCS extends ISyncManager {
47
- shared(matchingKey: string, readinessManager: IReadinessManager, storage: IStorageSync): ISyncManager | undefined
47
+ shared(matchingKey: string, readinessManager: IReadinessManager, storage: IStorageSync): Pick<ISyncManager, 'stop' | 'flush'> | undefined
48
48
  }
@@ -16,6 +16,7 @@ import { isConsumerMode } from '../utils/settingsValidation/mode';
16
16
  export function eventTrackerFactory(
17
17
  settings: ISettings,
18
18
  eventsCache: IEventsCacheBase,
19
+ whenInit: (cb: () => void) => void,
19
20
  integrationsManager?: IEventsHandler,
20
21
  telemetryCache?: ITelemetryCacheSync | ITelemetryCacheAsync
21
22
  ): IEventTracker {
@@ -31,14 +32,16 @@ export function eventTrackerFactory(
31
32
  if (tracked) {
32
33
  log.info(EVENTS_TRACKER_SUCCESS, [msg]);
33
34
  if (integrationsManager) {
34
- // Wrap in a timeout because we don't want it to be blocking.
35
- setTimeout(function () {
36
- // copy of event, to avoid unexpected behaviour if modified by integrations
37
- const eventDataCopy = objectAssign({}, eventData);
38
- if (properties) eventDataCopy.properties = objectAssign({}, properties);
39
- // integrationsManager does not throw errors (they are internally handled by each integration module)
40
- integrationsManager.handleEvent(eventDataCopy);
41
- }, 0);
35
+ whenInit(() => {
36
+ // Wrap in a timeout because we don't want it to be blocking.
37
+ setTimeout(() => {
38
+ // copy of event, to avoid unexpected behaviour if modified by integrations
39
+ const eventDataCopy = objectAssign({}, eventData);
40
+ if (properties) eventDataCopy.properties = objectAssign({}, properties);
41
+ // integrationsManager does not throw errors (they are internally handled by each integration module)
42
+ integrationsManager.handleEvent(eventDataCopy);
43
+ });
44
+ });
42
45
  }
43
46
  } else {
44
47
  log.error(ERROR_EVENTS_TRACKER, [msg]);
@@ -19,6 +19,7 @@ export function impressionsTrackerFactory(
19
19
  settings: ISettings,
20
20
  impressionsCache: IImpressionsCacheBase,
21
21
  strategy: IStrategy,
22
+ whenInit: (cb: () => void) => void,
22
23
  integrationsManager?: IImpressionsHandler,
23
24
  telemetryCache?: ITelemetryCacheSync | ITelemetryCacheAsync,
24
25
  ): IImpressionsTracker {
@@ -66,17 +67,19 @@ export function impressionsTrackerFactory(
66
67
  sdkLanguageVersion: version
67
68
  };
68
69
 
69
- // Wrap in a timeout because we don't want it to be blocking.
70
- setTimeout(function () {
71
- // integrationsManager.handleImpression does not throw errors
72
- if (integrationsManager) integrationsManager.handleImpression(impressionData);
70
+ whenInit(() => {
71
+ // Wrap in a timeout because we don't want it to be blocking.
72
+ setTimeout(() => {
73
+ // integrationsManager.handleImpression does not throw errors
74
+ if (integrationsManager) integrationsManager.handleImpression(impressionData);
73
75
 
74
- try { // @ts-ignore. An exception on the listeners should not break the SDK.
75
- if (impressionListener) impressionListener.logImpression(impressionData);
76
- } catch (err) {
77
- log.error(ERROR_IMPRESSIONS_LISTENER, [err]);
78
- }
79
- }, 0);
76
+ try { // @ts-ignore. An exception on the listeners should not break the SDK.
77
+ if (impressionListener) impressionListener.logImpression(impressionData);
78
+ } catch (err) {
79
+ log.error(ERROR_IMPRESSIONS_LISTENER, [err]);
80
+ }
81
+ });
82
+ });
80
83
  }
81
84
  }
82
85
  }
@@ -65,6 +65,7 @@ export interface IImpressionSenderAdapter {
65
65
 
66
66
  /** Unique keys tracker */
67
67
  export interface IUniqueKeysTracker {
68
+ start(): void;
68
69
  stop(): void;
69
70
  track(key: string, featureName: string): void;
70
71
  }
@@ -25,10 +25,6 @@ export function uniqueKeysTrackerFactory(
25
25
  ): IUniqueKeysTracker {
26
26
  let intervalId: any;
27
27
 
28
- if (filterAdapter.refreshRate) {
29
- intervalId = setInterval(filterAdapter.clear, filterAdapter.refreshRate);
30
- }
31
-
32
28
  return {
33
29
 
34
30
  track(key: string, featureName: string): void {
@@ -39,6 +35,12 @@ export function uniqueKeysTrackerFactory(
39
35
  uniqueKeysCache.track(key, featureName);
40
36
  },
41
37
 
38
+ start(): void {
39
+ if (filterAdapter.refreshRate) {
40
+ intervalId = setInterval(filterAdapter.clear, filterAdapter.refreshRate);
41
+ }
42
+ },
43
+
42
44
  stop(): void {
43
45
  clearInterval(intervalId);
44
46
  }
package/src/types.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ISplit, ISplitFiltersValidation } from './dtos/types';
1
+ import { ISplitFiltersValidation } from './dtos/types';
2
2
  import { IIntegration, IIntegrationFactoryParams } from './integrations/types';
3
3
  import { ILogger } from './logger/types';
4
4
  import { ISdkFactoryContext } from './sdkFactory/types';
@@ -98,7 +98,6 @@ export interface ISettings {
98
98
  eventsFirstPushWindow: number
99
99
  },
100
100
  readonly storage: IStorageSyncFactory | IStorageAsyncFactory,
101
- readonly preloadedData?: SplitIO.PreloadedData,
102
101
  readonly integrations: Array<{
103
102
  readonly type: string,
104
103
  (params: IIntegrationFactoryParams): IIntegration | void
@@ -772,20 +771,21 @@ export namespace SplitIO {
772
771
  * If this value is older than 10 days ago (expiration time policy), the data is not used to update the storage content.
773
772
  * @TODO configurable expiration time policy?
774
773
  */
775
- // lastUpdated: number,
774
+ lastUpdated: number,
776
775
  /**
777
776
  * Change number of the preloaded data.
778
777
  * If this value is older than the current changeNumber at the storage, the data is not used to update the storage content.
779
778
  */
780
779
  since: number,
781
780
  /**
782
- * List of feature flag definitions.
783
- * @TODO rename to flags
781
+ * Map of feature flags to their stringified definitions.
784
782
  */
785
- splitsData: ISplit[],
783
+ splitsData: {
784
+ [splitName: string]: string
785
+ },
786
786
  /**
787
787
  * Optional map of user keys to their list of segments.
788
- * @TODO rename to memberships
788
+ * @TODO remove when releasing first version
789
789
  */
790
790
  mySegmentsData?: {
791
791
  [key: string]: string[]
@@ -793,10 +793,9 @@ export namespace SplitIO {
793
793
  /**
794
794
  * Optional map of segments to their stringified definitions.
795
795
  * This property is ignored if `mySegmentsData` was provided.
796
- * @TODO rename to segments
797
796
  */
798
797
  segmentsData?: {
799
- [segmentName: string]: string[]
798
+ [segmentName: string]: string
800
799
  },
801
800
  }
802
801
  /**
@@ -3,6 +3,14 @@ import { ISettings, SDKMode } from '../../../types';
3
3
  import { ILogger } from '../../../logger/types';
4
4
  import { ERROR_STORAGE_INVALID } from '../../../logger/constants';
5
5
  import { LOCALHOST_MODE, STANDALONE_MODE, STORAGE_PLUGGABLE, STORAGE_LOCALSTORAGE, STORAGE_MEMORY } from '../../../utils/constants';
6
+ import { IStorageFactoryParams, IStorageSync } from '../../../storages/types';
7
+
8
+ export function __InLocalStorageMockFactory(params: IStorageFactoryParams): IStorageSync {
9
+ const result = InMemoryStorageCSFactory(params);
10
+ result.splits.checkCache = () => true; // to emit SDK_READY_FROM_CACHE
11
+ return result;
12
+ }
13
+ __InLocalStorageMockFactory.type = STORAGE_MEMORY;
6
14
 
7
15
  /**
8
16
  * This function validates `settings.storage` object
@@ -22,6 +30,11 @@ export function validateStorageCS(settings: { log: ILogger, storage?: any, mode:
22
30
  log.error(ERROR_STORAGE_INVALID);
23
31
  }
24
32
 
33
+ // In localhost mode with InLocalStorage, fallback to a mock InLocalStorage to emit SDK_READY_FROM_CACHE
34
+ if (mode === LOCALHOST_MODE && storage.type === STORAGE_LOCALSTORAGE) {
35
+ return __InLocalStorageMockFactory;
36
+ }
37
+
25
38
  if ([LOCALHOST_MODE, STANDALONE_MODE].indexOf(mode) === -1) {
26
39
  // Consumer modes require an async storage
27
40
  if (storage.type !== STORAGE_PLUGGABLE) throw new Error('A PluggableStorage instance is required on consumer mode');
@@ -9,6 +9,8 @@ export interface ISplitsEventEmitter extends IEventEmitter {
9
9
  once(event: ISplitsEvent, listener: (...args: any[]) => void): this;
10
10
  splitsArrived: boolean;
11
11
  splitsCacheLoaded: boolean;
12
+ initialized: boolean;
13
+ initCallbacks: (() => void)[];
12
14
  }
13
15
  /** Segments data emitter */
14
16
  declare type SDK_SEGMENTS_ARRIVED = 'state::segments-arrived';
@@ -46,6 +48,7 @@ export interface IReadinessManager {
46
48
  timeout(): void;
47
49
  setDestroyed(): void;
48
50
  destroy(): void;
51
+ init(): void;
49
52
  /** for client-side */
50
53
  shared(): IReadinessManager;
51
54
  }
@@ -63,6 +63,7 @@ export interface ISdkFactoryContextAsync extends ISdkFactoryContext {
63
63
  * Object parameter with the modules required to create an SDK factory instance
64
64
  */
65
65
  export interface ISdkFactoryParams {
66
+ lazyInit?: boolean;
66
67
  settings: ISettings;
67
68
  platform: IPlatform;
68
69
  storageFactory: (params: IStorageFactoryParams) => IStorageSync | IStorageAsync;
@@ -19,6 +19,11 @@ export declare abstract class AbstractSplitsCacheAsync implements ISplitsCacheAs
19
19
  abstract trafficTypeExists(trafficType: string): Promise<boolean>;
20
20
  abstract clear(): Promise<boolean | void>;
21
21
  usesSegments(): Promise<boolean>;
22
+ /**
23
+ * Check if the splits information is already stored in cache.
24
+ * Noop, just keeping the interface. This is used by client-side implementations only.
25
+ */
26
+ checkCache(): Promise<boolean>;
22
27
  /**
23
28
  * Kill `name` split and set `defaultTreatment` and `changeNumber`.
24
29
  * Used for SPLIT_KILL push notifications.
@@ -19,6 +19,11 @@ export declare abstract class AbstractSplitsCacheSync implements ISplitsCacheSyn
19
19
  abstract trafficTypeExists(trafficType: string): boolean;
20
20
  abstract usesSegments(): boolean;
21
21
  abstract clear(): void;
22
+ /**
23
+ * Check if the splits information is already stored in cache. This data can be preloaded.
24
+ * It is used as condition to emit SDK_SPLITS_CACHE_LOADED, and then SDK_READY_FROM_CACHE.
25
+ */
26
+ checkCache(): boolean;
22
27
  /**
23
28
  * Kill `name` split and set `defaultTreatment` and `changeNumber`.
24
29
  * Used for SPLIT_KILL push notifications.
@@ -1,21 +1,10 @@
1
1
  import { SplitIO } from '../types';
2
- import { ISegmentsCacheSync, ISplitsCacheSync, IStorageSync } from './types';
2
+ import { DataLoader } from './types';
3
3
  /**
4
- * Storage-agnostic adaptation of `loadDataIntoLocalStorage` function
5
- * (https://github.com/godaddy/split-javascript-data-loader/blob/master/src/load-data.js)
4
+ * Factory of client-side storage loader
6
5
  *
7
- * @param preloadedData validated data following the format proposed in https://github.com/godaddy/split-javascript-data-loader and extended with a `mySegmentsData` property.
8
- * @param storage object containing `splits` and `segments` cache (client-side variant)
9
- * @param userKey user key (matching key) of the provided MySegmentsCache
10
- *
11
- * @TODO extend to load largeSegments
12
- * @TODO extend to load data on shared mySegments storages. Be specific when emitting SDK_READY_FROM_CACHE on shared clients. Maybe the serializer should provide the `useSegments` flag.
13
- * @TODO add logs, and input validation in this module, in favor of size reduction.
14
- * @TODO unit tests
6
+ * @param preloadedData validated data following the format proposed in https://github.com/godaddy/split-javascript-data-loader
7
+ * and extended with a `mySegmentsData` property.
8
+ * @returns function to preload the storage
15
9
  */
16
- export declare function loadData(preloadedData: SplitIO.PreloadedData, storage: {
17
- splits?: ISplitsCacheSync;
18
- segments: ISegmentsCacheSync;
19
- largeSegments?: ISegmentsCacheSync;
20
- }, userKey?: string): void;
21
- export declare function getSnapshot(storage: IStorageSync, userKeys?: string[]): SplitIO.PreloadedData;
10
+ export declare function dataLoaderFactory(preloadedData: SplitIO.PreloadedData): DataLoader;
@@ -1,15 +1,15 @@
1
1
  import { ILogger } from '../../logger/types';
2
- import { AbstractSegmentsCacheSync } from '../AbstractSegmentsCacheSync';
2
+ import { AbstractMySegmentsCacheSync } from '../AbstractMySegmentsCacheSync';
3
3
  import type { MySegmentsKeyBuilder } from '../KeyBuilderCS';
4
- export declare class MySegmentsCacheInLocal extends AbstractSegmentsCacheSync {
4
+ export declare class MySegmentsCacheInLocal extends AbstractMySegmentsCacheSync {
5
5
  private readonly keys;
6
6
  private readonly log;
7
7
  constructor(log: ILogger, keys: MySegmentsKeyBuilder);
8
- addToSegment(name: string): boolean;
9
- removeFromSegment(name: string): boolean;
8
+ protected addSegment(name: string): boolean;
9
+ protected removeSegment(name: string): boolean;
10
10
  isInSegment(name: string): boolean;
11
11
  getRegisteredSegments(): string[];
12
12
  getKeysCount(): number;
13
- setChangeNumber(name?: string, changeNumber?: number): void;
13
+ protected setChangeNumber(changeNumber?: number): void;
14
14
  getChangeNumber(): number;
15
15
  }
@@ -35,6 +35,12 @@ export declare class SplitsCacheInLocal extends AbstractSplitsCacheSync {
35
35
  getSplitNames(): string[];
36
36
  trafficTypeExists(trafficType: string): boolean;
37
37
  usesSegments(): boolean;
38
+ /**
39
+ * Check if the splits information is already stored in browser LocalStorage.
40
+ * In this function we could add more code to check if the data is valid.
41
+ * @override
42
+ */
43
+ checkCache(): boolean;
38
44
  /**
39
45
  * Clean Splits cache if its `lastUpdated` timestamp is older than the given `expirationTimestamp`,
40
46
  *
@@ -1,15 +1,15 @@
1
- import { AbstractSegmentsCacheSync } from '../AbstractSegmentsCacheSync';
1
+ import { AbstractMySegmentsCacheSync } from '../AbstractMySegmentsCacheSync';
2
2
  /**
3
3
  * Default MySegmentsCacheInMemory implementation that stores MySegments in memory.
4
4
  * Supported by all JS runtimes.
5
5
  */
6
- export declare class MySegmentsCacheInMemory extends AbstractSegmentsCacheSync {
6
+ export declare class MySegmentsCacheInMemory extends AbstractMySegmentsCacheSync {
7
7
  private segmentCache;
8
8
  private cn?;
9
- addToSegment(name: string): boolean;
10
- removeFromSegment(name: string): boolean;
9
+ protected addSegment(name: string): boolean;
10
+ protected removeSegment(name: string): boolean;
11
11
  isInSegment(name: string): boolean;
12
- setChangeNumber(name?: string, changeNumber?: number): void;
12
+ protected setChangeNumber(changeNumber?: number): void;
13
13
  getChangeNumber(): number;
14
14
  getRegisteredSegments(): string[];
15
15
  getKeysCount(): number;
@@ -1,19 +1,17 @@
1
- import { AbstractSegmentsCacheSync } from '../AbstractSegmentsCacheSync';
1
+ import { ISegmentsCacheSync } from '../types';
2
2
  /**
3
- * Default ISplitsCacheSync implementation that stores split definitions in memory.
4
- * Supported by all JS runtimes.
3
+ * Default ISplitsCacheSync implementation for server-side that stores segments definitions in memory.
5
4
  */
6
- export declare class SegmentsCacheInMemory extends AbstractSegmentsCacheSync {
5
+ export declare class SegmentsCacheInMemory implements ISegmentsCacheSync {
7
6
  private segmentCache;
8
7
  private segmentChangeNumber;
9
- addToSegment(name: string, segmentKeys: string[]): boolean;
10
- removeFromSegment(name: string, segmentKeys: string[]): boolean;
8
+ update(name: string, addedKeys: string[], removedKeys: string[], changeNumber: number): boolean;
11
9
  isInSegment(name: string, key: string): boolean;
12
10
  clear(): void;
13
11
  private _registerSegment;
14
12
  registerSegments(names: string[]): boolean;
15
13
  getRegisteredSegments(): string[];
16
14
  getKeysCount(): number;
17
- setChangeNumber(name: string, changeNumber: number): boolean;
18
15
  getChangeNumber(name: string): number;
16
+ resetSegments(): boolean;
19
17
  }
@@ -3,7 +3,6 @@ import { AbstractSplitsCacheSync } from '../AbstractSplitsCacheSync';
3
3
  import { ISet } from '../../utils/lang/sets';
4
4
  /**
5
5
  * Default ISplitsCacheSync implementation that stores split definitions in memory.
6
- * Supported by all JS runtimes.
7
6
  */
8
7
  export declare class SplitsCacheInMemory extends AbstractSplitsCacheSync {
9
8
  private flagSetsFilter;
@@ -7,10 +7,13 @@ export declare class SegmentsCacheInRedis implements ISegmentsCacheAsync {
7
7
  private readonly redis;
8
8
  private readonly keys;
9
9
  constructor(log: ILogger, keys: KeyBuilderSS, redis: RedisAdapter);
10
- addToSegment(name: string, segmentKeys: string[]): Promise<boolean>;
11
- removeFromSegment(name: string, segmentKeys: string[]): Promise<boolean>;
10
+ /**
11
+ * Update the given segment `name` with the lists of `addedKeys`, `removedKeys` and `changeNumber`.
12
+ * The returned promise is resolved if the operation success, with `true` if the segment was updated (i.e., some key was added or removed),
13
+ * or rejected if it fails (e.g., Redis operation fails).
14
+ */
15
+ update(name: string, addedKeys: string[], removedKeys: string[], changeNumber: number): Promise<boolean>;
12
16
  isInSegment(name: string, key: string): Promise<boolean>;
13
- setChangeNumber(name: string, changeNumber: number): Promise<boolean>;
14
17
  getChangeNumber(name: string): Promise<number>;
15
18
  registerSegments(segments: string[]): Promise<boolean>;
16
19
  getRegisteredSegments(): Promise<string[]>;
@@ -10,28 +10,16 @@ export declare class SegmentsCachePluggable implements ISegmentsCacheAsync {
10
10
  private readonly wrapper;
11
11
  constructor(log: ILogger, keys: KeyBuilderSS, wrapper: IPluggableStorageWrapper);
12
12
  /**
13
- * Add a list of `segmentKeys` to the given segment `name`.
14
- * The returned promise is resolved when the operation success
15
- * or rejected if wrapper operation fails.
16
- */
17
- addToSegment(name: string, segmentKeys: string[]): Promise<boolean | void>;
18
- /**
19
- * Remove a list of `segmentKeys` from the given segment `name`.
20
- * The returned promise is resolved when the operation success
21
- * or rejected if wrapper operation fails.
13
+ * Update the given segment `name` with the lists of `addedKeys`, `removedKeys` and `changeNumber`.
14
+ * The returned promise is resolved if the operation success, with `true` if the segment was updated (i.e., some key was added or removed),
15
+ * or rejected if it fails (e.g., wrapper operation fails).
22
16
  */
23
- removeFromSegment(name: string, segmentKeys: string[]): Promise<boolean | void>;
17
+ update(name: string, addedKeys: string[], removedKeys: string[], changeNumber: number): Promise<boolean>;
24
18
  /**
25
19
  * Returns a promise that resolves with a boolean value indicating if `key` is part of `name` segment.
26
20
  * Promise can be rejected if wrapper operation fails.
27
21
  */
28
22
  isInSegment(name: string, key: string): Promise<boolean>;
29
- /**
30
- * Set till number for the given segment `name`.
31
- * The returned promise is resolved when the operation success,
32
- * or rejected if it fails (e.g., wrapper operation fails).
33
- */
34
- setChangeNumber(name: string, changeNumber: number): Promise<boolean | void>;
35
23
  /**
36
24
  * Get till number or -1 if it's not defined.
37
25
  * The returned promise is resolved with the changeNumber or -1 if it doesn't exist or a wrapper operation fails.