-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathSplitsCacheInLocal.ts
More file actions
311 lines (246 loc) · 9.43 KB
/
SplitsCacheInLocal.ts
File metadata and controls
311 lines (246 loc) · 9.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import { ISplit } from '../../dtos/types';
import { AbstractSplitsCacheSync, usesSegments } from '../AbstractSplitsCacheSync';
import { isFiniteNumber, toNumber, isNaNNumber } from '../../utils/lang';
import { KeyBuilderCS } from '../KeyBuilderCS';
import { ILogger } from '../../logger/types';
import { LOG_PREFIX } from './constants';
import { ISettings } from '../../types';
import { getStorageHash } from '../KeyBuilder';
import { setToArray } from '../../utils/lang/sets';
/**
* ISplitsCacheSync implementation that stores split definitions in browser LocalStorage.
*/
export class SplitsCacheInLocal extends AbstractSplitsCacheSync {
private readonly keys: KeyBuilderCS;
private readonly log: ILogger;
private readonly storageHash: string;
private readonly flagSetsFilter: string[];
private hasSync?: boolean;
private updateNewFilter?: boolean;
constructor(settings: ISettings, keys: KeyBuilderCS, expirationTimestamp?: number) {
super();
this.keys = keys;
this.log = settings.log;
this.storageHash = getStorageHash(settings);
this.flagSetsFilter = settings.sync.__splitFiltersValidation.groupedFilters.bySet;
this._checkExpiration(expirationTimestamp);
this._checkFilterQuery();
}
private _decrementCount(key: string) {
const count = toNumber(localStorage.getItem(key)) - 1;
// @ts-expect-error
if (count > 0) localStorage.setItem(key, count);
else localStorage.removeItem(key);
}
private _decrementCounts(split: ISplit | null) {
try {
if (split) {
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);
// @ts-expect-error
localStorage.setItem(ttKey, toNumber(localStorage.getItem(ttKey)) + 1);
if (usesSegments(split)) {
const segmentsCountKey = this.keys.buildSplitsWithSegmentCountKey();
// @ts-expect-error
localStorage.setItem(segmentsCountKey, toNumber(localStorage.getItem(segmentsCountKey)) + 1);
}
} catch (e) {
this.log.error(LOG_PREFIX + e);
}
}
/**
* 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.
*/
clear() {
this.log.info(LOG_PREFIX + 'Flushing Splits data from localStorage');
// collect item keys
const len = localStorage.length;
const accum = [];
for (let cur = 0; cur < len; cur++) {
const key = localStorage.key(cur);
if (key != null && this.keys.isSplitsCacheKey(key)) accum.push(key);
}
// remove items
accum.forEach(key => {
localStorage.removeItem(key);
});
this.hasSync = false;
}
addSplit(split: ISplit) {
try {
const name = split.name;
const splitKey = this.keys.buildSplitKey(name);
const splitFromLocalStorage = localStorage.getItem(splitKey);
const previousSplit = splitFromLocalStorage ? JSON.parse(splitFromLocalStorage) : null;
localStorage.setItem(splitKey, JSON.stringify(split));
this._incrementCounts(split);
this._decrementCounts(previousSplit);
if (previousSplit) this.removeFromFlagSets(previousSplit.name, previousSplit.sets);
this.addToFlagSets(split);
return true;
} catch (e) {
this.log.error(LOG_PREFIX + e);
return false;
}
}
removeSplit(name: string): boolean {
try {
const split = this.getSplit(name);
if (!split) return false;
localStorage.removeItem(this.keys.buildSplitKey(name));
this._decrementCounts(split);
if (split) this.removeFromFlagSets(split.name, split.sets);
return true;
} catch (e) {
this.log.error(LOG_PREFIX + e);
return false;
}
}
getSplit(name: string): ISplit | null {
const item = localStorage.getItem(this.keys.buildSplitKey(name));
return item && JSON.parse(item);
}
setChangeNumber(changeNumber: number): boolean {
// when using a new split query, we must update it at the store
if (this.updateNewFilter) {
this.log.info(LOG_PREFIX + 'SDK key, flags filter criteria or flags spec version was modified. Updating cache');
const storageHashKey = this.keys.buildHashKey();
try {
localStorage.setItem(storageHashKey, this.storageHash);
} catch (e) {
this.log.error(LOG_PREFIX + e);
}
this.updateNewFilter = false;
}
try {
localStorage.setItem(this.keys.buildSplitsTillKey(), changeNumber + '');
// update "last updated" timestamp with current time
localStorage.setItem(this.keys.buildLastUpdatedKey(), Date.now() + '');
this.hasSync = true;
return true;
} catch (e) {
this.log.error(LOG_PREFIX + e);
return false;
}
}
getChangeNumber(): number {
const n = -1;
let value: string | number | null = localStorage.getItem(this.keys.buildSplitsTillKey());
if (value !== null) {
value = parseInt(value, 10);
return isNaNNumber(value) ? n : value;
}
return n;
}
getSplitNames(): string[] {
const len = localStorage.length;
const accum = [];
let cur = 0;
while (cur < len) {
const key = localStorage.key(cur);
if (key != null && this.keys.isSplitKey(key)) accum.push(this.keys.extractKey(key));
cur++;
}
return accum;
}
trafficTypeExists(trafficType: string): boolean {
const ttCount = toNumber(localStorage.getItem(this.keys.buildTrafficTypeKey(trafficType)));
return isFiniteNumber(ttCount) && ttCount > 0;
}
usesSegments() {
// If cache hasn't been synchronized with the cloud, assume we need them.
if (!this.hasSync) return true;
const storedCount = localStorage.getItem(this.keys.buildSplitsWithSegmentCountKey());
const splitsWithSegmentsCount = storedCount === null ? 0 : toNumber(storedCount);
if (isFiniteNumber(splitsWithSegmentsCount)) {
return splitsWithSegmentsCount > 0;
} else {
return true;
}
}
/**
* Check if the splits information is already stored in browser LocalStorage.
* In this function we could add more code to check if the data is valid.
* @override
*/
checkCache(): boolean {
return this.getChangeNumber() > -1;
}
/**
* Clean Splits cache if its `lastUpdated` timestamp is older than the given `expirationTimestamp`,
*
* @param expirationTimestamp - if the value is not a number, data will not be cleaned
*/
private _checkExpiration(expirationTimestamp?: number) {
let value: string | number | null = localStorage.getItem(this.keys.buildLastUpdatedKey());
if (value !== null) {
value = parseInt(value, 10);
if (!isNaNNumber(value) && expirationTimestamp && value < expirationTimestamp) this.clear();
}
}
// @TODO eventually remove `_checkFilterQuery`. Cache should be cleared at the storage level, reusing same logic than PluggableStorage
private _checkFilterQuery() {
const storageHashKey = this.keys.buildHashKey();
const storageHash = localStorage.getItem(storageHashKey);
if (storageHash !== this.storageHash) {
try {
// mark cache to update the new query filter on first successful splits fetch
this.updateNewFilter = true;
// if there is cache, clear it
if (this.checkCache()) this.clear();
} catch (e) {
this.log.error(LOG_PREFIX + e);
}
}
// if the filter didn't change, nothing is done
}
getNamesByFlagSets(flagSets: string[]): Set<string>[] {
return flagSets.map(flagSet => {
const flagSetKey = this.keys.buildFlagSetKey(flagSet);
const flagSetFromLocalStorage = localStorage.getItem(flagSetKey);
return new Set(flagSetFromLocalStorage ? JSON.parse(flagSetFromLocalStorage) : []);
});
}
private addToFlagSets(featureFlag: ISplit) {
if (!featureFlag.sets) return;
featureFlag.sets.forEach(featureFlagSet => {
if (this.flagSetsFilter.length > 0 && !this.flagSetsFilter.some(filterFlagSet => filterFlagSet === featureFlagSet)) return;
const flagSetKey = this.keys.buildFlagSetKey(featureFlagSet);
const flagSetFromLocalStorage = localStorage.getItem(flagSetKey);
const flagSetCache = new Set(flagSetFromLocalStorage ? JSON.parse(flagSetFromLocalStorage) : []);
flagSetCache.add(featureFlag.name);
localStorage.setItem(flagSetKey, JSON.stringify(setToArray(flagSetCache)));
});
}
private removeFromFlagSets(featureFlagName: string, flagSets?: string[]) {
if (!flagSets) return;
flagSets.forEach(flagSet => {
this.removeNames(flagSet, featureFlagName);
});
}
private removeNames(flagSetName: string, featureFlagName: string) {
const flagSetKey = this.keys.buildFlagSetKey(flagSetName);
const flagSetFromLocalStorage = localStorage.getItem(flagSetKey);
if (!flagSetFromLocalStorage) return;
const flagSetCache = new Set(JSON.parse(flagSetFromLocalStorage));
flagSetCache.delete(featureFlagName);
if (flagSetCache.size === 0) {
localStorage.removeItem(flagSetKey);
return;
}
localStorage.setItem(flagSetKey, JSON.stringify(setToArray(flagSetCache)));
}
}