-
Notifications
You must be signed in to change notification settings - Fork 194
/
analytics.ts
730 lines (624 loc) · 20.7 KB
/
analytics.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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
//@ts-ignore
import type { Rule } from '@segment/tsub/dist/store';
import deepmerge from 'deepmerge';
import allSettled from 'promise.allsettled';
import { AppState, AppStateStatus } from 'react-native';
import { settingsCDN, workspaceDestinationFilterKey } from './constants';
import { getContext } from './context';
import {
applyRawEventData,
createAliasEvent,
createGroupEvent,
createIdentifyEvent,
createScreenEvent,
createTrackEvent,
} from './events';
import { CountFlushPolicy, TimerFlushPolicy } from './flushPolicies';
import { FlushPolicyExecuter } from './flushPolicies/flush-policy-executer';
import type { DestinationPlugin, PlatformPlugin, Plugin } from './plugin';
import { InjectContext } from './plugins/InjectContext';
import { InjectUserInfo } from './plugins/InjectUserInfo';
import { SegmentDestination } from './plugins/SegmentDestination';
import {
createGetter,
DeepLinkData,
Settable,
Storage,
Watchable,
} from './storage';
import { Timeline } from './timeline';
import type { DestinationFilters, SegmentAPISettings } from './types';
import {
Config,
Context,
DeepPartial,
GroupTraits,
IntegrationSettings,
JsonMap,
LoggerType,
PluginType,
SegmentAPIIntegrations,
SegmentEvent,
UpdateType,
UserInfoState,
UserTraits,
} from './types';
import { getPluginsWithFlush, getPluginsWithReset } from './util';
import { getUUID } from './uuid';
import type { FlushPolicy } from './flushPolicies';
type OnContextLoadCallback = (type: UpdateType) => void | Promise<void>;
type OnPluginAddedCallback = (plugin: Plugin) => void;
export class SegmentClient {
// the config parameters for the client - a merge of user provided and default options
private config: Config;
// Storage
private store: Storage;
// current app state
private appState: AppStateStatus | 'unknown' = 'unknown';
// subscription for propagating changes to appState
private appStateSubscription: any;
// logger
public logger: LoggerType;
// whether the user has called cleanup
private destroyed: boolean = false;
private isAddingPlugins: boolean = false;
private timeline: Timeline;
private pendingEvents: SegmentEvent[] = [];
private pluginsToAdd: Plugin[] = [];
private flushPolicyExecuter!: FlushPolicyExecuter;
private isInitialized = false;
// TODO: Refactor into Observable<T>
private isContextLoaded = false;
private onContextLoadedObservers: OnContextLoadCallback[] = [];
private onPluginAddedObservers: OnPluginAddedCallback[] = [];
private readonly platformPlugins: PlatformPlugin[] = [
new InjectUserInfo(),
new InjectContext(),
];
// Watchables
/**
* Access or subscribe to client context
*/
readonly context: Watchable<DeepPartial<Context> | undefined> &
Settable<DeepPartial<Context>>;
/**
* Access or subscribe to adTrackingEnabled (also accesible from context)
*/
readonly adTrackingEnabled: Watchable<boolean>;
/**
* Access or subscribe to integration settings
*/
readonly settings: Watchable<SegmentAPIIntegrations | undefined>;
/**
* Access or subscribe to destination filter settings
*/
readonly filters: Watchable<DestinationFilters | undefined>;
/**
* Access or subscribe to user info (anonymousId, userId, traits)
*/
readonly userInfo: Watchable<UserInfoState> & Settable<UserInfoState>;
readonly deepLinkData: Watchable<DeepLinkData>;
/**
* Returns the plugins currently loaded in the timeline
* @param ofType Type of plugins, defaults to all
* @returns List of Plugin objects
*/
getPlugins(ofType?: PluginType): readonly Plugin[] {
const plugins = { ...this.timeline.plugins };
if (ofType !== undefined) {
return [...(plugins[ofType] ?? [])];
}
return (
[
...this.getPlugins(PluginType.before),
...this.getPlugins(PluginType.enrichment),
...this.getPlugins(PluginType.utility),
...this.getPlugins(PluginType.destination),
...this.getPlugins(PluginType.after),
] ?? []
);
}
/**
* Retrieves a copy of the current client configuration
*/
getConfig() {
return { ...this.config };
}
constructor({
config,
logger,
store,
}: {
config: Config;
logger: LoggerType;
store: any;
}) {
this.logger = logger;
this.config = config;
this.store = store;
this.timeline = new Timeline();
// Initialize the watchables
this.context = {
get: this.store.context.get,
set: this.store.context.set,
onChange: this.store.context.onChange,
};
this.adTrackingEnabled = {
get: createGetter(
() => this.store.context.get()?.device?.adTrackingEnabled ?? false,
async () => {
const context = await this.store.context.get(true);
return context?.device?.adTrackingEnabled ?? false;
}
),
onChange: (callback: (value: boolean) => void) =>
this.store.context.onChange((context?: DeepPartial<Context>) => {
callback(context?.device?.adTrackingEnabled ?? false);
}),
};
this.settings = {
get: this.store.settings.get,
onChange: this.store.settings.onChange,
};
this.filters = {
get: this.store.filters.get,
onChange: this.store.filters.onChange,
};
this.userInfo = {
get: this.store.userInfo.get,
set: this.store.userInfo.set,
onChange: this.store.userInfo.onChange,
};
this.deepLinkData = {
get: this.store.deepLinkData.get,
onChange: this.store.deepLinkData.onChange,
};
// Watch for isReady so that we can handle any pending events
// Delays events processing in the timeline until the store is ready to prevent missing data injected from the plugins
this.store.isReady.onChange((value) => {
this.onStorageReady(value);
});
// add segment destination plugin unless
// asked not to via configuration.
if (this.config.autoAddSegmentDestination) {
const segmentDestination = new SegmentDestination();
this.add({ plugin: segmentDestination });
}
// Setup platform specific plugins
this.platformPlugins.forEach((plugin) => this.add({ plugin: plugin }));
// Start flush policies
this.setupFlushPolicies();
}
/**
* Initializes the client plugins, settings and subscribers.
* Can only be called once.
*/
async init() {
if (this.isInitialized) {
this.logger.warn('SegmentClient already initialized');
return;
}
await this.fetchSettings();
// flush any stored events
this.flushPolicyExecuter.manualFlush();
// set up tracking for lifecycle events
this.setupLifecycleEvents();
// check if the app was opened from a deep link
await this.trackDeepLinks();
// save the current installed version
await this.checkInstalledVersion();
this.isInitialized = true;
}
private generateFiltersMap(rules: Rule[]): DestinationFilters {
const map: DestinationFilters = {};
for (const r of rules) {
const key = r.destinationName ?? workspaceDestinationFilterKey;
map[key] = r;
}
return map;
}
async fetchSettings() {
const settingsEndpoint = `${settingsCDN}/${this.config.writeKey}/settings`;
try {
const res = await fetch(settingsEndpoint);
const resJson: SegmentAPISettings = await res.json();
const integrations = resJson.integrations;
const filters = this.generateFiltersMap(
resJson.middlewareSettings?.routingRules ?? []
);
this.logger.info(`Received settings from Segment succesfully.`);
await Promise.all([
this.store.settings.set(integrations),
this.store.filters.set(filters),
]);
} catch {
this.logger.warn(
`Could not receive settings from Segment. ${
this.config.defaultSettings
? 'Will use the default settings.'
: 'Device mode destinations will be ignored unless you specify default settings in the client config.'
}`
);
if (this.config.defaultSettings) {
await this.store.settings.set(this.config.defaultSettings.integrations);
}
}
}
/**
* There is no garbage collection in JS, which means that any listeners, timeouts and subscriptions
* would run until the application closes
*
* This method exists in case the user for some reason needs to recreate the class instance during runtime.
* In this case, they should run client.cleanup() to destroy the listeners in the old client before creating a new one.
*
* There is a Stage 3 EMCAScript proposal to add a user-defined finalizer, which we could potentially switch to if
* it gets approved: https://github.com/tc39/proposal-weakrefs#finalizers
*/
cleanup() {
this.flushPolicyExecuter.cleanup();
this.appStateSubscription?.remove();
this.destroyed = true;
this.isInitialized = false;
}
private setupLifecycleEvents() {
this.appStateSubscription?.remove();
this.appStateSubscription = AppState.addEventListener(
'change',
(nextAppState) => {
this.handleAppStateChange(nextAppState);
}
);
}
/**
Applies the supplied closure to the currently loaded set of plugins.
NOTE: This does not apply to plugins contained within DestinationPlugins.
- Parameter closure: A closure that takes an plugin to be operated on as a parameter.
*/
apply(closure: (plugin: Plugin) => void) {
this.timeline.apply(closure);
}
/**
* Adds a new plugin to the currently loaded set.
* @param {{ plugin: Plugin, settings?: IntegrationSettings }} Plugin to be added. Settings are optional if you want to force a configuration instead of the Segment Cloud received one
*/
add<P extends Plugin>({
plugin,
settings,
}: {
plugin: P;
settings?: P extends DestinationPlugin ? IntegrationSettings : never;
}) {
// plugins can either be added immediately or
// can be cached and added later during the next state update
// this is to avoid adding plugins before network requests made as part of setup have resolved
if (settings !== undefined && plugin.type === PluginType.destination) {
this.store.settings.add(
(plugin as unknown as DestinationPlugin).key,
settings
);
}
if (!this.store.isReady.get()) {
this.pluginsToAdd.push(plugin);
} else {
this.addPlugin(plugin);
}
}
private addPlugin(plugin: Plugin) {
plugin.configure(this);
this.timeline.add(plugin);
this.triggerOnPluginLoaded(plugin);
}
/**
Removes and unloads plugins with a matching name from the system.
- Parameter pluginName: An plugin name.
*/
remove({ plugin }: { plugin: Plugin }) {
this.timeline.remove(plugin);
}
async process(incomingEvent: SegmentEvent) {
const event = applyRawEventData(incomingEvent);
if (this.store.isReady.get() === true) {
this.flushPolicyExecuter.notify(event);
return this.timeline.process(event);
} else {
this.pendingEvents.push(event);
return event;
}
}
private async trackDeepLinks() {
if (this.getConfig().trackDeepLinks === true) {
const deepLinkProperties = await this.store.deepLinkData.get(true);
this.trackDeepLinkEvent(deepLinkProperties);
this.store.deepLinkData.onChange((data) => {
this.trackDeepLinkEvent(data);
});
}
}
private trackDeepLinkEvent(deepLinkProperties: DeepLinkData) {
if (deepLinkProperties.url !== '') {
const event = createTrackEvent({
event: 'Deep Link Opened',
properties: {
...deepLinkProperties,
},
});
this.process(event);
this.logger.info('TRACK (Deep Link Opened) event saved', event);
}
}
/**
* Executes when the state store is initialized.
* @param isReady
*/
private onStorageReady(isReady: boolean) {
if (isReady) {
// Add all plugins awaiting store
if (this.pluginsToAdd.length > 0 && !this.isAddingPlugins) {
this.isAddingPlugins = true;
try {
// start by adding the plugins
this.pluginsToAdd.forEach((plugin) => {
this.addPlugin(plugin);
});
// now that they're all added, clear the cache
// this prevents this block running for every update
this.pluginsToAdd = [];
} finally {
this.isAddingPlugins = false;
}
}
// Send all events in the queue
for (const e of this.pendingEvents) {
this.timeline.process(e);
}
this.pendingEvents = [];
}
}
async flush(): Promise<void> {
if (this.destroyed) {
return;
}
this.flushPolicyExecuter.reset();
const promises: (void | Promise<void>)[] = [];
getPluginsWithFlush(this.timeline).forEach((plugin) => {
promises.push(plugin.flush());
});
await allSettled(promises);
return Promise.resolve();
}
async screen(name: string, options?: JsonMap) {
const event = createScreenEvent({
name,
properties: options,
});
await this.process(event);
this.logger.info('SCREEN event saved', event);
}
async track(eventName: string, options?: JsonMap) {
const event = createTrackEvent({
event: eventName,
properties: options,
});
await this.process(event);
this.logger.info('TRACK event saved', event);
}
async identify(userId?: string, userTraits?: UserTraits) {
const event = createIdentifyEvent({
userId: userId,
userTraits: userTraits,
});
await this.process(event);
this.logger.info('IDENTIFY event saved', event);
}
async group(groupId: string, groupTraits?: GroupTraits) {
const event = createGroupEvent({
groupId,
groupTraits,
});
await this.process(event);
this.logger.info('GROUP event saved', event);
}
async alias(newUserId: string) {
const { anonymousId, userId: previousUserId } =
await this.store.userInfo.get(true);
const event = createAliasEvent({
anonymousId,
userId: previousUserId,
newUserId,
});
await this.process(event);
this.logger.info('ALIAS event saved', event);
}
/**
* Called once when the client is first created
*
* Detect and save the the currently installed application version
* Send application lifecycle events if trackAppLifecycleEvents is enabled
*
* Exactly one of these events will be sent, depending on the current and previous version:s
* Application Installed - no information on the previous version, so it's a fresh install
* Application Updated - the previous detected version is different from the current version
* Application Opened - the previously detected version is same as the current version
*/
private async checkInstalledVersion() {
const context = await getContext(undefined, this.config);
const previousContext = this.store.context.get();
// Only overwrite the previous context values to preserve any values that are added by enrichment plugins like IDFA
await this.store.context.set(deepmerge(previousContext ?? {}, context));
// Only callback during the intial context load
if (!this.isContextLoaded) {
this.triggerOnContextLoad(UpdateType.initial);
}
this.isContextLoaded = true;
if (!this.config.trackAppLifecycleEvents) {
return;
}
if (previousContext?.app === undefined) {
const event = createTrackEvent({
event: 'Application Installed',
properties: {
version: context.app.version,
build: context.app.build,
},
});
this.process(event);
this.logger.info('TRACK (Application Installed) event saved', event);
} else if (context.app.version !== previousContext.app.version) {
const event = createTrackEvent({
event: 'Application Updated',
properties: {
version: context.app.version,
build: context.app.build,
previous_version: previousContext.app.version,
previous_build: previousContext.app.build,
},
});
this.process(event);
this.logger.info('TRACK (Application Updated) event saved', event);
}
const event = createTrackEvent({
event: 'Application Opened',
properties: {
from_background: false,
version: context.app.version,
build: context.app.build,
},
});
this.process(event);
this.logger.info('TRACK (Application Opened) event saved', event);
}
/**
* AppState event listener. Called whenever the app state changes.
*
* Send application lifecycle events if trackAppLifecycleEvents is enabled.
*
* Application Opened - only when the app state changes from 'inactive' or 'background' to 'active'
* The initial event from 'unknown' to 'active' is handled on launch in checkInstalledVersion
* Application Backgrounded - when the app state changes from 'inactive' or 'background' to 'active
*
* @param nextAppState 'active', 'inactive', 'background' or 'unknown'
*/
private handleAppStateChange(nextAppState: AppStateStatus) {
if (this.config.trackAppLifecycleEvents) {
if (
['inactive', 'background'].includes(this.appState) &&
nextAppState === 'active'
) {
const context = this.store.context.get();
const event = createTrackEvent({
event: 'Application Opened',
properties: {
from_background: true,
version: context?.app?.version,
build: context?.app?.build,
},
});
this.process(event);
this.logger.info('TRACK (Application Opened) event saved', event);
} else if (
this.appState === 'active' &&
['inactive', 'background'].includes(nextAppState)
) {
const event = createTrackEvent({
event: 'Application Backgrounded',
});
this.process(event);
this.logger.info('TRACK (Application Backgrounded) event saved', event);
}
}
this.appState = nextAppState;
}
reset(resetAnonymousId: boolean = true) {
const anonymousId =
resetAnonymousId === true
? getUUID()
: this.store.userInfo.get().anonymousId;
this.store.userInfo.set({
anonymousId,
userId: undefined,
traits: undefined,
});
getPluginsWithReset(this.timeline).forEach((plugin) => plugin.reset());
this.logger.info('Client has been reset');
}
/**
* Registers a callback for when the client has loaded the device context. This happens at the startup of the app, but
* it is handy for plugins that require context data during configure as it guarantees the context data is available.
*
* If the context is already loaded it will call the callback immediately.
*
* @param callback Function to call when context is ready.
*/
onContextLoaded(callback: OnContextLoadCallback) {
this.onContextLoadedObservers.push(callback);
if (this.isContextLoaded) {
this.triggerOnContextLoad(UpdateType.initial);
}
}
private triggerOnContextLoad(type: UpdateType) {
this.onContextLoadedObservers.map((f) => f?.(type));
}
/**
* Registers a callback for each plugin that gets added to the analytics client.
* @param callback Function to call
*/
onPluginLoaded(callback: OnPluginAddedCallback) {
this.onPluginAddedObservers.push(callback);
}
private triggerOnPluginLoaded(plugin: Plugin) {
this.onPluginAddedObservers.map((f) => f?.(plugin));
}
/**
* Initializes the flush policies from config and subscribes to updates to
* trigger flush
*/
private setupFlushPolicies() {
let flushPolicies = this.config.flushPolicies ?? [];
// Compatibility with older arguments
if (
this.config.flushAt !== undefined &&
this.config.flushAt !== null &&
this.config.flushAt > 0
) {
flushPolicies.push(new CountFlushPolicy(this.config.flushAt));
}
if (
this.config.flushInterval !== undefined &&
this.config.flushInterval !== null &&
this.config.flushInterval > 0
) {
flushPolicies.push(
new TimerFlushPolicy(this.config.flushInterval * 1000)
);
}
this.flushPolicyExecuter = new FlushPolicyExecuter(flushPolicies, () => {
this.flush();
});
}
/**
* Adds a FlushPolicy to the list
* @param policies policies to add
*/
addFlushPolicy(...policies: FlushPolicy[]) {
for (const policy of policies) {
this.flushPolicyExecuter.add(policy);
}
}
/**
* Removes a FlushPolicy from the execution
*
* @param policies policies to remove
* @returns true if the value was removed, false if not found
*/
removeFlushPolicy(...policies: FlushPolicy[]) {
for (const policy of policies) {
this.flushPolicyExecuter.remove(policy);
}
}
/**
* Returns the current enabled flush policies
*/
getFlushPolicies() {
return this.flushPolicyExecuter.policies;
}
}