-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathindex.ts
530 lines (467 loc) · 15.6 KB
/
index.ts
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
import jwt_decode from 'jwt-decode'
import mitt, { EventType, WildcardHandler } from 'mitt'
import { EventSourcePolyfill } from './eventsource'
import type {
Options,
Target,
StreamEvent,
EventOnBinding,
EventOffBinding,
Result,
Evaluation,
VariationValue,
MetricsInfo
} from './types'
import { Event } from './types'
import { logError, defaultOptions, METRICS_FLUSH_INTERVAL } from './utils'
const SDK_VERSION = '1.4.11'
const METRICS_VALID_COUNT_INTERVAL = 500
const fetch = globalThis.fetch
const EventSource = EventSourcePolyfill
// Flag to detect is Proxy is supported (not under IE 11)
const hasProxy = !!globalThis.Proxy
const convertValue = (evaluation: Evaluation) => {
let { value } = evaluation
try {
switch (evaluation.kind.toLowerCase()) {
case 'int':
case 'number':
value = Number(value)
break
case 'boolean':
value = value.toString().toLowerCase() === 'true'
break
case 'json':
value = JSON.parse(value as string)
break
}
} catch (error) {
logError(error)
}
return value
}
const initialize = (apiKey: string, target: Target, options?: Options): Result => {
let closed = false
let environment: string
let clusterIdentifier: string
let eventSource: any
let jwtToken: string
let metricsSchedulerId: number
let metricsCollectorEnabled = true
const stopMetricsCollector = () => {
metricsCollectorEnabled = false
}
const startMetricsCollector = () => {
metricsCollectorEnabled = true
}
let metrics: Array<MetricsInfo> = []
const eventBus = mitt()
const configurations = { ...defaultOptions, ...options }
const logDebug = (message: string, ...args: any[]) => {
if (configurations.debug) {
// tslint:disable-next-line:no-console
console.debug(`[FF-SDK] ${message}`, ...args)
}
}
const updateMetrics = (metricsInfo: MetricsInfo) => {
if (metricsCollectorEnabled) {
const now = Date.now()
if (now - metricsInfo.lastAccessed > METRICS_VALID_COUNT_INTERVAL) {
metricsInfo.count++
metricsInfo.lastAccessed = now
}
}
}
globalThis.onbeforeunload = () => {
if (metrics.length && globalThis.localStorage) {
stopMetricsCollector()
globalThis.localStorage.HARNESS_FF_METRICS = JSON.stringify(metrics)
startMetricsCollector()
}
}
const authenticate = async (clientID: string, configuration: Options): Promise<string> => {
const response = await fetch(`${configuration.baseUrl}/client/auth`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ apiKey: clientID, target })
})
const data: { authToken: string } = await response.json()
return data.authToken
}
const scheduleSendingMetrics = () => {
if (metrics.length) {
logDebug('Sending metrics...', { metrics, evaluations })
const payload = {
metricsData: metrics.map(entry => ({
timestamp: Date.now(),
count: entry.count,
metricsType: 'FFMETRICS',
attributes: [
{
key: 'featureIdentifier',
value: entry.featureIdentifier
},
{
key: 'featureName',
value: entry.featureIdentifier
},
{
key: 'variationIdentifier',
value: entry.variationIdentifier
},
{
key: 'target',
value: target.identifier
},
{
key: 'SDK_NAME',
value: 'JavaScript'
},
{
key: 'SDK_LANGUAGE',
value: 'JavaScript'
},
{
key: 'SDK_TYPE',
value: 'client'
},
{
key: 'SDK_VERSION',
value: SDK_VERSION
}
]
}))
}
fetch(`${configurations.eventUrl}/metrics/${environment}?cluster=${clusterIdentifier}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${jwtToken}` },
body: JSON.stringify(payload)
})
.then(() => {
metrics = []
})
.catch(error => {
logDebug(error)
})
.finally(() => {
metricsSchedulerId = window.setTimeout(scheduleSendingMetrics, METRICS_FLUSH_INTERVAL)
})
} else {
metricsSchedulerId = window.setTimeout(scheduleSendingMetrics, METRICS_FLUSH_INTERVAL)
}
}
let evaluations: Record<string, Evaluation> = {}
const sendEvent = (evaluation: Evaluation) => {
logDebug('Sending event for', evaluation.flag)
if (hasProxy) {
eventBus.emit(
Event.CHANGED,
new Proxy(evaluation, {
get(_flagInfo, property) {
if (_flagInfo.hasOwnProperty(property) && property === 'value') {
// only track metric when value is read
const featureIdentifier = _flagInfo.flag
const featureValue = evaluation.value
const entry = metrics.find(
_entry => _entry.featureIdentifier === featureIdentifier && _entry.featureValue === featureValue
)
if (entry) {
updateMetrics(entry)
entry.variationIdentifier = evaluations[featureIdentifier]?.identifier || ''
} else {
metrics.push({
featureIdentifier,
featureValue: String(featureValue),
variationIdentifier: evaluations[featureIdentifier].identifier || '',
count: metricsCollectorEnabled ? 1 : 0,
lastAccessed: Date.now()
})
}
logDebug('Metrics event: Flag', property, 'has been read with value via stream update', featureValue)
}
return property === 'value' ? convertValue(evaluation) : evaluation[property]
}
})
)
} else {
eventBus.emit(Event.CHANGED, {
deleted: evaluation.deleted,
flag: evaluation.flag,
value: convertValue(evaluation)
})
}
}
const creatStorage = function () {
return hasProxy
? new Proxy(
{},
{
get(_storage, property) {
const _value = _storage[property]
if (_storage.hasOwnProperty(property)) {
const featureValue = _storage[property]
// TODO/BUG: This logic to collect metrics will fail when two variations have the same value
// Need to find a better way
const entry = metrics.find(
_entry => _entry.featureIdentifier === property && featureValue === _entry.featureValue
)
if (entry) {
entry.variationIdentifier = evaluations[property as string]?.identifier || ''
updateMetrics(entry)
} else {
metrics.push({
featureIdentifier: property as string,
featureValue,
variationIdentifier: evaluations[property as string]?.identifier || '',
count: metricsCollectorEnabled ? 1 : 0,
lastAccessed: Date.now()
})
}
logDebug(
'Metrics event: Flag:',
property,
'has been read with value:',
featureValue,
'variationIdentifier:',
evaluations[property as string]?.identifier
)
}
return _value
}
}
)
: {}
}
let storage: Record<string, any> = creatStorage()
authenticate(apiKey, configurations)
.then((token: string) => {
if (closed) return
jwtToken = token
const decoded: { environment: string; clusterIdentifier: string } = jwt_decode(token)
logDebug('Authenticated', decoded)
if (globalThis.localStorage && globalThis.localStorage.HARNESS_FF_METRICS) {
try {
// metrics = JSON.parse(globalThis.localStorage.HARNESS_FF_METRICS)
delete globalThis.localStorage.HARNESS_FF_METRICS
logDebug('Picking up metrics from previous session')
} catch (error) {}
}
metricsSchedulerId = window.setTimeout(scheduleSendingMetrics, METRICS_FLUSH_INTERVAL)
environment = decoded.environment
clusterIdentifier = decoded.clusterIdentifier
// When authentication is done, fetch all flags
fetchFlags()
.then(() => {
logDebug('Fetch all flags ok', storage)
})
.then(() => {
if (closed) return
startStream() // start stream only after we get all evaluations
})
.then(() => {
if (closed) return
logDebug('Event stream ready', { storage })
eventBus.emit(Event.READY, { ...storage })
if (!hasProxy) {
Object.keys(storage).forEach(key => {
metrics.push({
featureIdentifier: key,
featureValue: storage[key],
variationIdentifier: evaluations[key]?.identifier || '',
count: metricsCollectorEnabled ? 1 : 0,
lastAccessed: Date.now()
})
})
}
})
.catch(err => {
eventBus.emit(Event.ERROR, err)
})
})
.catch(error => {
logError('Authentication error: ', error)
eventBus.emit(Event.ERROR, error)
})
const fetchFlags = async () => {
try {
const res = await fetch(
`${configurations.baseUrl}/client/env/${environment}/target/${target.identifier}/evaluations?cluster=${clusterIdentifier}`,
{
headers: {
Authorization: `Bearer ${jwtToken}`
}
}
)
const data = await res.json()
data.forEach((_evaluation: Evaluation) => {
const _value = convertValue(_evaluation)
// Update the flag if the values are different
const _oldValue = storage[_evaluation.flag]
if (_value !== _oldValue) {
logDebug('Flag variation has changed for ', _evaluation.identifier)
storage[_evaluation.flag] = _value
evaluations[_evaluation.flag] = { ..._evaluation, value: _value }
sendEvent(_evaluation)
}
})
} catch (error) {
logError('Features fetch operation error: ', error)
eventBus.emit(Event.ERROR, error)
return error
}
}
const fetchFlag = async (identifier: string) => {
try {
const result = await fetch(
`${configurations.baseUrl}/client/env/${environment}/target/${target.identifier}/evaluations/${identifier}?cluster=${clusterIdentifier}`,
{
headers: {
Authorization: `Bearer ${jwtToken}`
}
}
)
if (result.ok) {
const flagInfo: Evaluation = await result.json()
const _value = convertValue(flagInfo)
stopMetricsCollector()
storage[identifier] = _value
evaluations[identifier] = { ...flagInfo, value: _value }
startMetricsCollector()
sendEvent(flagInfo)
if (!hasProxy) {
const featureIdentifier = flagInfo.flag
const entry = metrics.find(
_entry => _entry.featureIdentifier === featureIdentifier && _entry.featureValue === flagInfo.value
)
if (entry) {
updateMetrics(entry)
entry.variationIdentifier = evaluations[featureIdentifier as string]?.identifier || ''
} else {
metrics.push({
featureIdentifier: featureIdentifier as string,
featureValue: String(flagInfo.value),
variationIdentifier: evaluations[featureIdentifier].identifier || '',
count: metricsCollectorEnabled ? 1 : 0,
lastAccessed: Date.now()
})
}
}
} else {
eventBus.emit(Event.ERROR, result)
}
} catch (error) {
logError('Feature fetch operation error: ', error)
eventBus.emit(Event.ERROR, error)
}
}
const startStream = () => {
// TODO: Implement polling when stream is disabled
if (!configurations.streamEnabled) {
logDebug('Stream is disabled by configuration. Note: Polling is not yet supported')
return
}
eventSource = new EventSource(`${configurations.baseUrl}/stream?cluster=${clusterIdentifier}`, {
headers: {
Authorization: `Bearer ${jwtToken}`,
'API-Key': apiKey
}
})
eventSource.onopen = (event: any) => {
logDebug('Stream connected', event)
eventBus.emit(Event.CONNECTED)
}
eventSource.onclose = (event: any) => {
logDebug('Stream disconnected')
eventBus.emit(Event.DISCONNECTED)
}
eventSource.onerror = (event: any) => {
logError('Stream has issue', event)
eventBus.emit(Event.ERROR, event)
}
const handleFlagEvent = (event: StreamEvent): void => {
switch (event.event) {
case 'create':
setTimeout(() => fetchFlag(event.identifier), 1000) // Wait a bit before fetching evaluation due to https://harness.atlassian.net/browse/FFM-583
break
case 'patch':
fetchFlag(event.identifier)
break
case 'delete':
delete storage[event.identifier]
eventBus.emit(Event.CHANGED, { flag: event.identifier, value: undefined, deleted: true })
logDebug('Evaluation deleted', { message: event, storage })
break
}
}
const handleSegmentEvent = (event: StreamEvent): void => {
if (event.event === 'patch') {
fetchFlags()
}
}
eventSource.addEventListener('*', (msg: any) => {
const event: StreamEvent = JSON.parse(msg.data)
logDebug('Received event from stream: ', event)
if (event.domain === 'flag') {
handleFlagEvent(event)
} else if (event.domain === 'target-segment') {
handleSegmentEvent(event)
}
})
}
const on: EventOnBinding = (event, callback) =>
eventBus.on((event as unknown) as EventType, (callback as unknown) as WildcardHandler)
const off: EventOffBinding = (event, callback) => {
if (event) {
eventBus.off((event as unknown) as '*', (callback as unknown) as WildcardHandler)
} else {
close()
}
}
const variation = (flag: string, defaultValue: any) => {
const value = storage[flag]
if (!hasProxy && value !== undefined) {
const featureValue = value
const featureIdentifier = flag
const entry = metrics.find(
_entry => _entry.featureIdentifier === featureIdentifier && _entry.featureValue === featureValue
)
if (entry) {
updateMetrics(entry)
entry.variationIdentifier = evaluations[featureIdentifier as string]?.identifier || ''
} else {
metrics.push({
featureIdentifier: featureIdentifier as string,
featureValue,
count: metricsCollectorEnabled ? 1 : 0,
variationIdentifier: evaluations[featureIdentifier].identifier || '',
lastAccessed: Date.now()
})
}
}
return value !== undefined ? value : defaultValue
}
const close = () => {
closed = true
logDebug('Closing event stream')
storage = creatStorage()
evaluations = {}
clearTimeout(metricsSchedulerId)
eventBus.all.clear()
if (typeof eventSource?.close === 'function') {
eventSource.close()
}
}
return { on, off, variation, close }
}
export {
initialize,
Options,
Target,
StreamEvent,
Event,
EventOnBinding,
EventOffBinding,
Result,
Evaluation,
VariationValue
}