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
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
|
import { loggerNamed } from '@amp-metrics/mt-client-logger-core';
import { reflect, network as network$1 } from '@amp-metrics/mt-metricskit-utils-private';
/*
* src/environment.js
* mt-event-queue
*
* Copyright © 2016-2019 Apple Inc. All rights reserved.
*
*/
var environment = {
/**
************************************ PUBLIC METHODS/IVARS ************************************
*/
/**
* Allows replacement of one or more of this class' functions
* Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
* To replace *all* methods of his class, simply have your delegate implement all the methods of this class
* Your delegate can be a true object instance, an anonymous object, or a class object.
* Your delegate is free to have as many additional non-matching methods as it likes.
* It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
*
* "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
* This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
* If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
* then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
* but override the "appVersion" method again, this time with their own supplied delegate.
*
* NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
* This allows the delegate to, essentially, call "super" before or after it does some work.
* If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
* @example:
* To override one or more methods, in place:
* eventRecorder.setDelegate({recordEvent: itms.recordEvent});
* To override one or more methods with a separate object:
* eventRecorder.setDelegate(eventRecorderDelegate);
* (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
* var eventRecorderDelegate = {recordEvent: itms.recordEvent,
* sendMethod: 'itms'};
* To override one or more methods with an instantiated object from a class definition:
* eventRecorder.setDelegate(new EventRecorderDelegate());
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
* EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
* return 'itms';
* };
* To override one or more methods with a class object (with "static" methods):
* eventRecorder.setDelegate(EventRecorderDelegate);
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.recordEvent = itms.recordEvent;
* EventRecorderDelegate.sendMethod = function sendMethod() {
* return 'itms';
* };
* @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
* @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
* otherwise returns false.
*/
setDelegate: function setDelegate(delegate) {
return reflect.attachDelegate(this, delegate);
},
/**
* An object that conforms to the WindowOrWorkerGlobalScope API:
* https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope
* @return {WindowOrWorkerGlobalScope}
*/
globalScope: function globalScope() {
return reflect.globalScope();
}
};
/*
* src/utils/constants.js
* mt-event-queue
*
* Copyright © 2019 Apple Inc. All rights reserved.
*
*/
// These constants are exposed publicly
/**
* Possible send method types to record events
*/
var SEND_METHOD = {
AJAX: 'ajax',
AJAX_SYNCHRONOUS: 'ajaxSynchronous',
IMAGE: 'image',
BEACON: 'beacon',
BEACON_SYNCHRONOUS: 'beaconSynchronous'
};
/*
* src/event_recorder/base.js
* mt-event-queue
*
* Copyright © 2016-2019 Apple Inc. All rights reserved.
*
*/
var IDENTIFIABLE_FIELDS = ['dsId', 'consumerId'];
/**
* Clone the passed-in source config with the provided topic
*
* Since we support multiple config instances instead of singleton config in mt-client-config.
* We have to pass the topicConfig instance to all places that we were passing a topic string to in the past.
* The problem there was if a caller wants to send an event to a sub-topic of the config and the config has some overriding values for the sub-topic,
* we need both config and the sub-topic to collect the values for the sub-topic.
* we either have to pass topicConfig and the sub-topic everywhere or create a new config with the sub-topic based on the topic config of the main topic.
* So we clone a new config by the main topic config with the sub-topic in the root entry(evenRecorder.recordEvent()) then all related logic would use that cloned config to load the config for the sub topic
*
* NOTE: We create an object and put the main topic config to the prototype of it because in that way,
* the cloned config still be able to share the same functions from the source config and when the source config getting cleanup, the cloned config also gets cleanup.
* The main purpose of the clone is overriding the main topic with the passed-in topic
*
* For Example:
* // We have a topic config with "topic_A" as the main topic, and a "topic_B" as the sub-topic inside of the config
* var topicConfig = {
* metricsUrl: 'https://xp.apple.com/report',
* postFrequency: 60000
* topic_B: {
* postFrequency: 30000
* }
* };
* var metricsKit = new MetricsKit('topic_A'); // which will have the above topicConfig for "topic_A"
* var eventFields = metricsKit.eventHandlers.enter.metricsData();
* var eventRecorder = new EventRecorder(metricsKit);
* eventRecorder.recordEvent('topic_B', eventFields);
*
* For above example, the recordEvent function will clone a new config by the topicConfig(topic_A) with the "topic_B".
* So underneath of the event recorder, we could get the correct values for "topic_B"
* topicConfig.value('postFrequency'); -> 30000
* event_queue.metricsUrlForConfig() -> https://xp.apple.com/report/topic_B
*
* @param sourceConfig
* @param topic
*/
function cloneTopicConfigWithTopic(sourceConfig, topic) {
var clonedConfig = {
_topic: topic
};
// inherit the class to have fields, methods and delegated methods from the source config
Object.setPrototypeOf(clonedConfig, sourceConfig);
return clonedConfig;
}
/**
* Abstract Event Recorder class
* @constructor
*/
var Base = function Base(configInstance) {
this._validateConfig(configInstance);
// @private
this._config = configInstance;
// @private
this._topicConfigCache = {};
// @private
this._topicPropsCache = {};
this.logger = loggerNamed('mt-event-queue');
};
/**
* Previously, this private method validated the config from metricskit but now it will validate the
* config directly
*
* @param {Object} config Configuration object
*/
Base.prototype._validateConfig = function validateConfig(config) {
var errorPostfix = 'please call constructor with a valid Config instance first.';
if (!config) {
throw new TypeError('Unable to find config, ' + errorPostfix);
} else if (!config.topic || !reflect.isFunction(config.topic)) {
throw new TypeError('Unable to find config.topic function, ' + errorPostfix);
} else if (
!config.metricsDisabledOrDenylistedEvent ||
!reflect.isFunction(config.metricsDisabledOrDenylistedEvent)
) {
throw new TypeError('Unable to find config.metricsDisabledOrDenylistedEvent function, ' + errorPostfix);
} else if (!config.removeDenylistedFields || !reflect.isFunction(config.removeDenylistedFields)) {
throw new TypeError('Unable to find config.removeDenylistedFields function, ' + errorPostfix);
}
};
/**
* Remove identify fields from the eventFields based on the topic properties
* @param {String} topic defines the Figaro "topic" that this event should be stored under
* @param {Object} eventFields a JavaScript object which will be converted to a JSON string and sent to AMP Analytics immediately.
* @private
*/
Base.prototype._removeIdentifiableFieldsForTopic = function _removeIdentifiableFieldsForTopic(topic, eventFields) {
this._topicPropsCache[topic] = this._topicPropsCache[topic] || {};
if (this._topicPropsCache[topic].anonymous) {
IDENTIFIABLE_FIELDS.forEach(function (field) {
delete eventFields[field];
});
}
};
/**
* Record event
* Subclasses implement this method to handle how to record an event
* @abstract
* @param {Object} eventFields a JavaScript object which will be converted to a JSON string and sent to AMP Analytics immediately.
* @returns {Promise}
*/
Base.prototype._record = function _record(eventFields) {};
/**
* clean resources of event recorder
* Subclasses implement this method to handle how to clean resources
* @returns {Promise} returns a Promise if the cleanup will asynchronously execute or undefined for synchronously executing
*/
Base.prototype.cleanup = function cleanup() {
this._config = null;
this._topicConfigCache = null;
this._topicPropsCache = {};
};
/**
* Records an event as JSON
* TODO: We should look at simplifying the process of using multiple topics. By deprecating recordEvent(topic, eventFields) in favor of recordEvent(eventFields) using the topic from the Kit.
* @param {String} topic an 'override' topic which will override the main topic.
* NOTE:
* 1. RecordEvent needs to check the denylisted event/fields. The passed-in topic may not be enough to check them. If MetricsKit's config had a subsection for the passed-in topic, then the denylisting would work properly.
* 2. The eventFields were generated with the config of Metricskit. If sending them to another topic, the eventFields might have incorrect values.
* @param {Object} eventFields a JavaScript object which will be converted to a JSON string and sent to AMP Analytics immediately.
* @returns {Promise} a Promise that returns the recorded event, or "null" if no object was recorded (e.g. if "eventFields" is null, or "disabled" is true, eventFields.eventType is one of the denylistedEvents, etc.)
*/
Base.prototype.recordEvent = function recordEvent(topic, eventFields) {
if (!this._config || !eventFields) {
return Promise.resolve(null);
}
var config = this._config;
var self = this;
var args = arguments;
// We do this if `topic` is a sub-topic of the configuration
if (reflect.isDefinedNonNullNonEmpty(topic) && topic !== config.topic()) {
config = this._topicConfigCache[topic];
if (!config) {
config = this._topicConfigCache[topic] = cloneTopicConfigWithTopic(this._config, topic);
}
}
// NOTE: Typically all event_handlers will check for this as well because that way if a client overrides "recordEvent", these checks will still take effect.
// We also test it here in case someone creates their own event_handler, we'd still want to exclude what needs to be excluded, in case they don't.
return config
.metricsDisabledOrDenylistedEvent(eventFields.eventType)
.then(function (disabledOrBlacklistedEvent) {
if (disabledOrBlacklistedEvent) {
return null;
}
return config
.removeDenylistedFields(eventFields)
.then(function () {
self._removeIdentifiableFieldsForTopic(topic, eventFields);
return self._record.apply(self, [config].concat(Array.prototype.slice.call(args, 1)));
})
.then(function () {
return eventFields;
});
})
.catch(function (error) {
self.logger.error(error);
return null;
});
};
/**
* The methodology being used to send batches of events to the server
* This field should be hardcoded in the client based on what method it is using to encode and send its events to Figaro.
* The three typical values are:
* "itms" - use this value when/if JavaScript code enqueues events for sending via the "itms.recordEvent()" method in ITML.
* "itunes" - use this value when/if JavaScript code enqueues events by calling the "iTunes.recordEvent()" method in Desktop Store apps.
* "javascript" - use this value when/if JavaScript code enqueues events for sending via the JavaScript eventQueue management. This is typically only used by older clients which don't have the built-in functionality of itms or iTunes available to them.
* @example "itms", "itunes", "javascript"
* @returns {String}
*/
Base.prototype.sendMethod = function sendMethod() {
return 'javascript';
};
/**
* Set related properties for the giving topic
* @param {String} topic defines the Figaro "topic" that this event should be stored under
* @param {Object} properties the properties for the topic
* @param {Boolean} properties.anonymous true if sending all events for the topic with credentials omitted(no cookies, no PII fields)
*/
Base.prototype.setProperties = function setProperties(topic, properties) {
this._topicPropsCache[topic] = this._topicPropsCache[topic] || {};
this._topicPropsCache[topic] = properties;
};
/*
* src/network.js
* mt-event-queue
*
* Copyright © 2017 Apple Inc. All rights reserved.
*
*/
/**
* Network request methods exposed so delegate callers can override
* @constructor
*/
var network = {
/**
* Allows replacement of one or more of this class' functions
* Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
* To replace *all* methods of his class, simply have your delegate implement all the methods of this class
* Your delegate can be a true object instance, an anonymous object, or a class object.
* Your delegate is free to have as many additional non-matching methods as it likes.
* It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
*
* "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
* This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
* If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
* then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
* but override the "appVersion" method again, this time with their own supplied delegate.
*
* NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
* This allows the delegate to, essentially, call "super" before or after it does some work.
* If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
* @example:
* To override one or more methods, in place:
* eventRecorder.setDelegate({recordEvent: itms.recordEvent});
* To override one or more methods with a separate object:
* eventRecorder.setDelegate(eventRecorderDelegate);
* (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
* var eventRecorderDelegate = {recordEvent: itms.recordEvent,
* sendMethod: 'itms'};
* To override one or more methods with an instantiated object from a class definition:
* eventRecorder.setDelegate(new EventRecorderDelegate());
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
* EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
* return 'itms';
* };
* To override one or more methods with a class object (with "static" methods):
* eventRecorder.setDelegate(EventRecorderDelegate);
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.recordEvent = itms.recordEvent;
* EventRecorderDelegate.sendMethod = function sendMethod() {
* return 'itms';
* };
* @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
* @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
* otherwise returns false.
*/
setDelegate: function setDelegate(delegate) {
return reflect.attachDelegate(this, delegate);
},
/**
* Covers private util network functions for delegation
*/
makeAjaxRequest: network$1.makeAjaxRequest
};
/*
* src/event_queue.js
* mt-event-queue
*
* A low-level, cross-platform, metrics batcher and emitter.
* Adapted from Jingle (its.MetricsQueue)
*
* Copyright © 2016-2017 Apple Inc. All rights reserved.
*
*/
/**
* Some ugly user agent detection, because iOS browsers refuse to send image pings onpagehide
* @return {Boolean} true if this browser is running on an iOS device
*/
function _isIOS() {
var userAgent = navigator.userAgent;
// IE for Windows Phone 8.1 contains the string 'iPhone', so we have to check for that too...
// https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
return /iPad|iPhone|iPod/.test(userAgent) && userAgent.indexOf('IEMobile') == -1;
}
/**
* Check if the fetch API is supported by the Browser and check if "keepalive" is available by checking for Firefox
* @returns {Boolean} true if fetch API is supported
*/
function _isFetchAndKeepaliveAvailable() {
return reflect.isFunction(environment.globalScope().fetch) && !/Firefox/.test(navigator.userAgent);
}
function _logger() {
return loggerNamed('mt-event-queue');
}
var CONSTANTS = {
DEFAULT_REQUEST_TIMEOUT: 10000, // TODO: move to config
EVENTS_KEY: 'events',
EVENT_DELIVERY_VERSION: '1.0',
MAX_PERSISTENT_QUEUE_SIZE: 100, // TODO: move to config
RETRY_EXPONENT_BASE: 2, // TODO: move to config
SEND_METHOD: SEND_METHOD,
URL_DELIVERY_VERSION: 2,
PROPERTIES_KEY: 'properties'
};
var _eventQueue = {
/**
* A dictionary of event queues by topic
* Each topic queue is an object that holds an array of the events themselves and information about send attempts for that topic (postIntervalToken, retryAttempts)
* We use an in-memory queue for two reasons:
* 1) We expect all remaining events to get sent on app exit via flushUnreportedEvents (ignoring the failed send case)
* 2) Stringifying and writing is expensive - as much as 5ms to write 100 events to localStorage on an older (2013) mobile device,
* and that would have to happen each time we did an event insertion, since localStorage only allows the saving of stringified (serialized) data.
*/
eventQueues: {},
/**
* Determines whether events will be sent via a post interval.
* If this value is false then the client must perform flushing manually and events will not be scheduled or sent automatically.
*/
postIntervalEnabled: true,
/**
* Enqueue an event to a particular topic queue
* @param {Object} topicConfig a config instance for the Figaro "topic" that this event should be stored under
* @param {Object} eventFields a JavaScript object which will be converted to a JSON string and enqued for sending to Figaro according to the postFrequency schedule
* @return {Promise} a Promise that returns the current event, if it was successfully queued, otherwise null
*/
enqueueEvent: function enqueueEvent(topicConfig, eventFields) {
if (topicConfig && eventFields && topicConfig.topic()) {
var topic = topicConfig.topic();
_eventQueue.eventQueues = _eventQueue.eventQueues || {};
_eventQueue.eventQueues[topic] = _eventQueue.eventQueues[topic] || {};
_eventQueue.eventQueues[topic].topicConfig = topicConfig;
_eventQueue.eventQueues[topic].flushConfig = _eventQueue.eventQueues[topic].flushConfig || {};
_eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY] =
_eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY] || [];
_eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY].push(eventFields); // Add the new event to the end of our eventQueue
// Set flushing related config values
if (Object.keys(_eventQueue.eventQueues[topic].flushConfig).length === 0) {
Promise.all([
topicConfig.value('metricsUrl'),
topicConfig.value('requestTimeout'),
topicConfig.value('postFrequency')
]).then(function (results) {
var flushConfig = _eventQueue.eventQueues[topic].flushConfig;
flushConfig.metricsUrl = results[0];
flushConfig.requestTimeout = results[1];
flushConfig.postFrequency = results[2];
});
}
return topicConfig.value('maxPersistentQueueSize').then(function (maxQueueSize) {
maxQueueSize = maxQueueSize || CONSTANTS.MAX_PERSISTENT_QUEUE_SIZE;
_eventQueue.trimEventQueues(_eventQueue.eventQueues, maxQueueSize);
return eventFields;
});
} else {
return Promise.resolve(null);
}
},
/**
* Currently this just ensures that each queue is <= maxEventsPerQueue, but in the future we could remove oldest events in a queue-independent way
* @param {Object} eventQueues a dictionary of event queues (arrays) by topic
* @param {int} maxEventsPerQueue
*/
trimEventQueues: function trimEventQueues(eventQueues, maxEventsPerQueue) {
var topics = Object.keys(eventQueues);
if (topics.length) {
topics.forEach(function (topic) {
var events = eventQueues[topic][CONSTANTS.EVENTS_KEY];
if (events && events.length && events.length > maxEventsPerQueue) {
_logger().warn(
'eventQueue overflow, deleting LRU events: size is: ' +
events.length +
' which is over max size: ' +
maxEventsPerQueue
);
eventQueues[topic][CONSTANTS.EVENTS_KEY] = events.slice(-maxEventsPerQueue);
}
});
}
},
/**
* Clears an event queue for a topic
* @param {String} topic defines the Figaro "topic" queue that should be cleared
*/
resetTopicQueue: function resetTopicQueue(topic) {
if (_eventQueue.eventQueues[topic]) {
_eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY] = null;
}
},
/**
* Resets the retry attempt counter for a topic, called when a send for that topic is successful
* @param {String} topic defines the Figaro "topic" queue whose counter should be cleared
*/
resetTopicRetryAttempts: function resetTopicRetryAttempts(topic) {
if (_eventQueue.eventQueues[topic]) {
_eventQueue.eventQueues[topic].retryAttempts = 0;
}
},
/**
* Increments the retry attempt counter for a topic, called when a send for that topic results in a 5XX response
* Sets the next send time for the topic according to an exponential backoff strategy
* @param {Object} A config for the Figaro "topic" queue whose counter should be incremented
* @returns {Promise}
*/
scheduleNextTopicRetryAttempt: function scheduleNextTopicRetryAttempt(topicConfig) {
var topic = topicConfig.topic();
if (_eventQueue.eventQueues[topic] && this.postIntervalEnabled) {
return topicConfig.value('postFrequency').then(function (postFrequency) {
var topicEventQueue = _eventQueue.eventQueues[topic];
topicEventQueue.retryAttempts = topicEventQueue.retryAttempts || 0;
topicEventQueue.retryAttempts++;
var nextSendTime =
Math.pow(CONSTANTS.RETRY_EXPONENT_BASE, topicEventQueue.retryAttempts) * postFrequency;
_eventQueue.resetTopicPostInterval(topic);
_eventQueue.setTopicPostInterval(topicConfig, nextSendTime);
});
} else {
return Promise.resolve();
}
},
/**
* Send queued events to the ingestion server
* If a particular topic send has previously failed, RETRY_BACKOFF_SKIP_COUNT_KEY will be nonzero, indicating we should skip sending that number of times
* @param {String} sendMethod "image" or "ajax" (default) or "ajaxSynchronous"
* @param {Boolean} postNow will be true when clients force a send outside of the regular postFrequency interval
* @returns {Promise}
*/
sendEvents: function sendEvents(sendMethod, postNow) {
var sendingTasks = [];
for (var topic in _eventQueue.eventQueues) {
var topicConfig = _eventQueue.eventQueues[topic].topicConfig;
var sendingPromise = _eventQueue.sendEventsForTopicConfig(topicConfig, sendMethod, postNow);
sendingTasks.push(sendingPromise);
}
return Promise.all(sendingTasks);
},
/**
* Send events for a single topic queue
* @param {Object} topicConfig defines the Figaro "topic" queue
* @param {String} sendMethod "image" or "ajax" (default) or "ajaxSynchronous"
* @param {Boolean} postNow will be true when clients force a send outside of the regular postFrequency interval
* @returns {Promise}
*/
sendEventsForTopicConfig: function sendEventsForTopicConfig(topicConfig, sendMethod, postNow) {
var topic = topicConfig.topic();
var topicQueue = _eventQueue.eventQueues[topic];
return Promise.all([
topicConfig.value('testExponentialBackoff'),
topicConfig.value('metricsUrl'),
topicConfig.disabled(),
topicConfig.value('postFrequency')
]).then(function (outputs) {
var testExponentialBackoff = outputs[0];
var metricsUrl = outputs[1];
var topicDisabled = outputs[2];
var postFrequency = outputs[3];
if (topicQueue && metricsUrl && !topicDisabled && !testExponentialBackoff) {
// Do not send if we are trying to postNow in the middle of a backoff
if (!(topicQueue.retryAttempts && postNow)) {
// The rule is "we post every postFrequency milliseconds", so even if it's been less than that (e.g. postNow), we reset
_eventQueue.resetTopicPostInterval(topic);
_eventQueue.setTopicPostInterval(topicConfig, postFrequency);
var sendingPromise;
switch (sendMethod) {
case CONSTANTS.SEND_METHOD.IMAGE:
sendingPromise = _eventQueue.sendEventsViaImage(topicConfig);
break;
case CONSTANTS.SEND_METHOD.BEACON:
sendingPromise = _eventQueue.sendEventsViaBeacon(topicConfig);
break;
case CONSTANTS.SEND_METHOD.AJAX_SYNCHRONOUS:
sendingPromise = _eventQueue.sendEventsViaAjax(topicConfig, false);
break;
case CONSTANTS.SEND_METHOD.AJAX: /* falls through */
default:
sendingPromise = _eventQueue.sendEventsViaAjax(topicConfig, true);
break;
}
return sendingPromise;
}
}
// Fail automatically if test flag present
else if (testExponentialBackoff) {
return _eventQueue.scheduleNextTopicRetryAttempt(topicConfig);
}
});
},
/**
* Makes one image ping per event in a queue of events, then clears the queue
* This is typically called on page / app close when the JS context is about to disappear and thus we will not know if the events made it to the server
* Current testing shows that browsers support 100+ image pings sent onpagehide, but we may need to alter our approach if this becomes unreliable
* (For example, we could send multiple events in a single ping instead, but there might be URL length issues in IE)
* @param {Object} topicConfig a config instance for the Figaro "topic" to send to
* @returns {Promise}
*/
sendEventsViaImage: function sendEventsViaImage(topicConfig) {
var topic = topicConfig.topic();
var returnedPromise = Promise.resolve();
if (_eventQueue.eventQueues[topic]) {
returnedPromise = resolveTopicConfigWithCallback(topicConfig, function (resolvedTopicConfig) {
var topicUrl = resolvedTopicConfig.metricsUrl;
var qpSeparator = topicUrl.indexOf('?') == -1 ? '?' : '&';
var imageBaseUrl = topicUrl + qpSeparator + 'responseType=image';
var events = _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY];
if (events && events.length) {
events.forEach(function (event) {
var imageParams = _eventQueue.createQueryParams(event);
if (imageParams) {
var imgUrl = imageBaseUrl + '&' + imageParams;
var imgObject = new Image();
var properties = _eventQueue.eventQueues[topic][CONSTANTS.PROPERTIES_KEY];
if (properties && properties.anonymous) {
imgObject.setAttribute('crossOrigin', 'anonymous');
}
imgObject.src = imgUrl;
}
});
}
_eventQueue.resetTopicQueue(topic);
});
}
return returnedPromise;
},
/**
* Convert an event object into a query parameter string, without a leading separator
* Guaranteed to return "null" if there are no event fields
* @param {Object} event key/value pairs containing event data
*/
createQueryParams: function createQueryParams(event) {
var val;
var stringVal;
var returnValue = '';
Object.keys(event).forEach(function (key, index, eventKeys) {
val = event[key];
// do not double-encode strings otherwise they will be reported as: '<value>'
stringVal = reflect.isString(val) ? val : JSON.stringify(val);
returnValue += key + '=' + encodeURIComponent(stringVal);
if (index < eventKeys.length - 1) {
// don't add a trailing ampersand
returnValue += '&';
}
});
return returnValue.length ? returnValue : null;
},
/**
* Makes one AJAX request per topic and clears the queue for that topic on success
* If any queue fails, retry using an exponential backoff strategy for that queue
* Refer to Metrics documentation for more details
* @param {Object} topicConfig a config instance for the Figaro "topic" to send to
* @param {Boolean} async - send asynchronously
* @returns {Promise}
*/
sendEventsViaAjax: function sendEventsViaAjax(topicConfig, async) {
var returnedPromise = Promise.resolve();
var topic = topicConfig.topic();
if (_eventQueue.eventQueues[topic] && _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY]) {
// Store events to be sent and reset the queue
var events = _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY];
var jsonEventsString = enrichAndSerializeEvents(events);
_eventQueue.resetTopicQueue(topic);
if (jsonEventsString) {
returnedPromise = resolveTopicConfigWithCallback(topicConfig, function (resolvedTopicConfig) {
var topicUrl = resolvedTopicConfig.metricsUrl;
var requestTimeout = resolvedTopicConfig.requestTimeout;
var resetRetryAttempts = function resetRetryAttempts() {
_eventQueue.resetTopicRetryAttempts(topic);
};
var onAjaxFailure = function onAjaxFailure(error, statusCode) {
// We're being told not to keep resending these events.
if (statusCode >= 400 && statusCode < 500) {
resetRetryAttempts();
} else {
// Prepend the events that failed to send back onto the queue
var newEvents = _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY] || [];
_eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY] = events.concat(newEvents);
_eventQueue.scheduleNextTopicRetryAttempt(topicConfig);
}
};
var eventQueueProps = _eventQueue.eventQueues[topic][CONSTANTS.PROPERTIES_KEY] || {};
var options = {
async: async,
timeout: requestTimeout
};
if (eventQueueProps.anonymous) {
options.withCredentials = false;
}
network.makeAjaxRequest(topicUrl, 'POST', jsonEventsString, resetRetryAttempts, onAjaxFailure, options);
});
}
}
return returnedPromise;
},
/**
* Makes an HTTP POST request via navigator.sendBeacon() if it is in the environment.
* Note: The sendBeacon() method returns true if the user agent successfully queued the data for transfer, otherwise false.
* sendBeacon() always includes credentials, so we fallback to the IMAGE/AJAX_SYNCHRONOUS methods to handle the anonymous use case.
* While testing out possible failures of sendBeacon(), the only 2 cases we encountered was using a non-"simple" content type like "application/json",
* or by passing data that is too large. Both cases would lead to failures when retrying, so retrying logic has intentionally been omitted in this approach.
* @param {Object} topicConfig a config instance for the Figaro "topic" to send to
*/
sendEventsViaBeacon: function sendEventsViaBeacon(topicConfig) {
var sendPromise = Promise.resolve();
if (!reflect.isFunction(navigator.sendBeacon)) {
_logger().error('navigator.sendBeacon() is not available in the environment');
return sendPromise;
}
var topic = topicConfig.topic();
var topicQueue = _eventQueue.eventQueues[topic];
if (topicQueue) {
var eventQueueProps = topicQueue[CONSTANTS.PROPERTIES_KEY];
// Fallback to other send methods to handle the anonymous use case
if (eventQueueProps && eventQueueProps.anonymous) {
// using fetch with keepalive to send events to fix the large event content issue (impressions field).
if (_isFetchAndKeepaliveAvailable()) {
sendPromise = _eventQueue.sendEventsViaFetch(topicConfig, { keepalive: true });
} else if (_isIOS()) {
// iOS browsers do not allow image pings to send onpagehide; use (deprecated) synchronous AJAX in those browsers
sendPromise = _eventQueue.sendEventsViaAjax(topicConfig, false);
} else {
sendPromise = _eventQueue.sendEventsViaImage(topicConfig);
}
} else {
var jsonEventsString = enrichAndSerializeEvents(topicQueue[CONSTANTS.EVENTS_KEY]);
if (jsonEventsString) {
_eventQueue.resetTopicQueue(topic);
sendPromise = resolveTopicConfigWithCallback(topicConfig, function (resolvedTopicConfig) {
var topicUrl = resolvedTopicConfig.metricsUrl;
var Blob = environment.globalScope().Blob;
var eventsBlob = new Blob([jsonEventsString], { type: 'application/json' });
var beaconResponse = navigator.sendBeacon(topicUrl, eventsBlob);
if (!beaconResponse) {
_logger().error('navigator.sendBeacon() was unable to queue the data for transfer');
}
});
}
}
}
return sendPromise;
},
/**
* Makes an HTTP POST request via fetch()
* @param {Object} topicConfig a config instance for the Figaro "topic" to send to
* @param {Object} options an object contains the options of fetch API
* @param {Boolean} options.keepalive whether allow the request to outlive the page
*/
sendEventsViaFetch: function sendEventsViaFetch(topicConfig, options) {
var sendPromise = Promise.resolve();
var topic = topicConfig.topic();
var topicQueue = _eventQueue.eventQueues[topic];
var keepalive = reflect.isDefinedNonNull(options) ? options.keepalive : null;
if (reflect.isDefinedNonNull(topicQueue)) {
var jsonEventsString = enrichAndSerializeEvents(topicQueue[CONSTANTS.EVENTS_KEY]);
if (jsonEventsString) {
_eventQueue.resetTopicQueue(topic);
var eventQueueProps = topicQueue[CONSTANTS.PROPERTIES_KEY] || {};
sendPromise = resolveTopicConfigWithCallback(topicConfig, function (resolvedTopicConfig) {
var topicUrl = resolvedTopicConfig.metricsUrl;
reflect.globalScope().fetch(topicUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: jsonEventsString,
credentials: eventQueueProps.anonymous === true ? 'omit' : 'same-origin',
keepalive: reflect.isDefinedNonNull(keepalive) ? keepalive : true
});
});
}
}
return sendPromise;
},
/**
* If no postInterval is currently set, sets postInterval to "postInterval"
* Note: Currently, only _sendEvents calls this function, but in the future, if other callers wanted to set a new interval due to, say, a config change,
* then events enqueued under the old postFrequency time will now have to wait (or be expedited) to the new time. To fix this, when any old
* interval fires, the callback can check to see if the interval passed in is different than _eventQueue.postIntervalToken and if so, it will tear down its timer.
* @param {Object} topic config
* @param {int} postInterval in ms
*/
setTopicPostInterval: function setTopicPostInterval(topicConfig, postInterval) {
var topic = topicConfig.topic();
if (_eventQueue.eventQueues[topic] && postInterval && this.postIntervalEnabled) {
this.resetTopicPostInterval(topic);
_eventQueue.eventQueues[topic].postIntervalToken = environment
.globalScope()
.setInterval(function onPostIntervalTrigger() {
_logger().debug(
'MetricsKit: triggering postIntervalTimer for ' + topic + ' at ' + new Date().toString()
);
_eventQueue.sendEventsForTopicConfig(topicConfig);
}, postInterval);
}
},
resetTopicPostInterval: function resetTopicPostInterval(topic) {
if (_eventQueue.eventQueues[topic]) {
environment.globalScope().clearInterval(_eventQueue.eventQueues[topic].postIntervalToken);
_eventQueue.eventQueues[topic].postIntervalToken = null;
}
},
resetQueuePostIntervals: function resetQueuePostIntervals() {
for (var topic in _eventQueue.eventQueues) {
_eventQueue.resetTopicPostInterval(topic);
}
},
setQueuePostIntervals: function setQueuePostIntervals() {
var tasks = [];
var setTopicPostIntervalFn = function (topicConfig) {
return function (postFrequency) {
_eventQueue.setTopicPostInterval(topicConfig, postFrequency);
};
};
for (var topic in _eventQueue.eventQueues) {
var events = _eventQueue.eventQueues[topic][CONSTANTS.EVENTS_KEY];
var topicConfig = _eventQueue.eventQueues[topic].topicConfig;
if (events && events.length) {
var taskPromise = topicConfig.value('postFrequency').then(setTopicPostIntervalFn(topicConfig));
tasks.push(taskPromise);
}
}
return Promise.all(tasks);
},
/**
* Determines whether the object contains the provided value.
* Note that values that are functions will be ignored.
* @param {Object} object the object whose values will be evaluated
* @param {Any} value the requested value to search for on the provided object
* @returns {Boolean} whether the object contains the value
* TODO: consider moving to utils
*/
objectContainsValue: function objectContainsValue(object, value) {
var result = false;
for (var property in object) {
var aValue = object[property];
if (object.hasOwnProperty(property) && !reflect.isFunction(aValue) && aValue === value) {
result = true;
break;
}
}
return result;
},
/**
* Set event queue related properties for the giving topic
* @param {String} topic defines the Figaro "topic" that this event should be stored under
* @param {Object} properties the event queue properties for the topic
* @param {Boolean} properties.anonymous true if sending all events for the topic with credentials omitted(no cookies, no PII fields)
*/
setProperties: function setProperties(topic, properties) {
_eventQueue.eventQueues = _eventQueue.eventQueues || {};
_eventQueue.eventQueues[topic] = _eventQueue.eventQueues[topic] || {};
_eventQueue.eventQueues[topic][CONSTANTS.PROPERTIES_KEY] = properties;
}
};
/**
************************************ PSEUDO-PRIVATE METHODS/IVARS ************************************
* These functions need to be accessible for ease of testing, but should not be used by clients
*/
function _utQueue() {
return _eventQueue;
}
/**
************************************ PUBLIC METHODS/IVARS ************************************
*/
/**
* Adds all the supplemental fields like "postTime", etc.
* Guaranteed to return "null" if there are no events
* @param {Array} eventQueue a list of events to send
* @return A stringified version of our eventQueue as a batch, including supplementary top-level fields, all ready to deliver in a ping
*/
function enrichAndSerializeEvents(eventQueue) {
var eventsBatchString = null;
if (eventQueue && eventQueue.length) {
var eventsDict = {};
eventsDict['deliveryVersion'] = CONSTANTS.EVENT_DELIVERY_VERSION;
eventsDict['postTime'] = Date.now();
eventsDict[CONSTANTS.EVENTS_KEY] = eventQueue;
try {
eventsBatchString = JSON.stringify(eventsDict);
} catch (e) {
_logger().error('Error stringifying events as JSON: ' + e);
}
}
return eventsBatchString;
}
function enrichAndSerializeEvent(event) {
return enrichAndSerializeEvents([event]);
}
/**
* @param {Object} topicConfig instance
* @return {Promise} a Promise that returns the metrics URL for this topic
*/
function metricsUrlForConfig(topicConfig) {
return topicConfig.value('metricsUrl').then(function (metricsUrl) {
var baseMetricsUrl = metricsUrl + '/' + CONSTANTS.URL_DELIVERY_VERSION + '/';
return baseMetricsUrl + topicConfig.topic();
});
}
/**
* This method is used to hide the topicConfig.value implementation for multiple properties, in order to support async and sync logic in sendEventsViaAjax().
* @param {Object} topicConfig an instance of TopicConfig(with a method named "value" and returns Promise from it) or an object that contains the "metricsUrl" and "topic()" properties
* @param {Function} callback a function to invoke with an object has metricsUrl, requestTimeout
*/
function resolveTopicConfigWithCallback(topicConfig, callback) {
if (!reflect.isFunction(callback)) {
_logger().warn('No callback function is provided for resolveTopicConfigWithCallback()');
return;
}
if (reflect.isString(topicConfig.metricsUrl) && !reflect.isFunction(topicConfig.value)) {
var topic = reflect.isFunction(topicConfig.topic) ? topicConfig.topic() : topicConfig.topic;
var metricsUrl = topicConfig.metricsUrl + '/' + CONSTANTS.URL_DELIVERY_VERSION + '/' + topic;
var requestTimeout = topicConfig.requestTimeout || CONSTANTS.DEFAULT_REQUEST_TIMEOUT;
var postFrequency = topicConfig.postFrequency;
return callback({
requestTimeout: Math.min(requestTimeout, postFrequency),
metricsUrl: metricsUrl
});
} else {
return Promise.all([
topicConfig.value('requestTimeout'),
topicConfig.value('postFrequency'),
metricsUrlForConfig(topicConfig)
]).then(function (outputs) {
var requestTimeout = outputs[0] || CONSTANTS.DEFAULT_REQUEST_TIMEOUT;
var postFrequency = outputs[1];
var metricsUrl = outputs[2];
return callback({
requestTimeout: Math.min(requestTimeout, postFrequency),
metricsUrl: metricsUrl
});
});
}
}
/**
* @param {Object} topicConfig instance
* @return {Promise} a Promise that returns the request timeout for this config
* Defaults to CONSTANTS.DEFAULT_REQUEST_TIMEOUT
*/
function requestTimeoutForConfig(topicConfig) {
return Promise.all([topicConfig.value('requestTimeout'), topicConfig.value('postFrequency')]).then(function (
outputs
) {
var requestTimeout = outputs[0] || CONSTANTS.DEFAULT_REQUEST_TIMEOUT;
var postFrequency = outputs[1];
return Math.min(requestTimeout, postFrequency);
});
}
/**
* Determines whether events will be sent via a post interval.
* If this value is false then the client must perform flushing manually and events will not be scheduled or sent automatically.
* @param {Bool} enabled whether the postInterval is enabled or not
* @returns {Promise}
*/
function setPostIntervalEnabled(enabled) {
_eventQueue.postIntervalEnabled = enabled;
if (enabled) {
return _eventQueue.setQueuePostIntervals();
} else {
return Promise.resolve(_eventQueue.resetQueuePostIntervals());
}
}
/**
* Enqueues events to be sent to the server in batches after "postFrequency" milliseconds since the previous send.
* The queue is stored in memory, and will retry on failed sends for as long as the session is open.
* Immediately before a page turn/tab close (usually onpagehide), clients can call flushUnreportedEvents() to send up any events still left in the queue.
*
* Flow:
* 1. Normal:
* a. [recordEvent()} Events posted to in-memory eventQueue via "recordEvent() (this method)".
* NOTE1: Only remember the most recent MAX_PERSISTENT_QUEUE_SIZE events per queue so we don't eat up all browser memory if we can't send for a very long time.
* NOTE2: We could have another set of "waitingForAck" queues which was also in-memory, but then
* we'd need code to merge two queues on re-tries (since _sendEvents() already merges in previously-queued events before attempting to [re]send)
* Since the send failure case is a rare case anyway, we err on the side of not adding code complexity to deal with it.
* b. [_sendEvents()] Wait "_postFrequency()" milliseconds before attempting actual "_sendEvents()"
* c. Set a timeout for the send which should be the lower of "_postFrquency()" or config.requestTimeout (which defaults to DEFAULT_REQUEST_TIMEOUT).
* This guarantees that only one send attempt per topic is pending at any given time.
* d. Wait for status=200 response ack, and clear event queue when received (see "Edge Cases", below)
* 2. Unsent due to ingestion server problem (5XX response):
* a. Continue gathering events, adding to in-memory eventQueue
* b. Use an exponential back-off strategy by waiting 2^1 = times "_postFrequency()" milliseconds before attempting another "_sendEvents()", as in "Normal" case, above
* c. If the ingestion server responds with another 5XX code, wait 2^2 = 4 times "_postFrequency()" milliseconds before attempting another send, and so on
* d. Continue as in 1c, above
* 3. Unsent due to failed conection or other error:
* a. Continue gathering events, adding to in-memory eventQueue
* b. Wait "_postFrequency()" milliseconds before attempting another "_sendEvents()", as in "Normal" case, above
* c. Continue as in 1c, above
*
* Edge Cases: Here are the small edge-case windows of failure in the in-memory event queue facility:
* 1. If two batches of events are sent out before the first one returns and clears the queue, the second one will try to send any queued events as well.
* For this to happen, we'd have to be in a situation where we're not leaving the page, event sends are taking some time to respond,
* causing us to build up a queue, and then two "sends" are attempted back-to-back by a client calling recordEvent() with postNow=true or flushUnreportedEvents().
* It's so rare that the code complexity to try and prevent this case is not worth it (synchronous event posting is the most straightforward way to handle it).
* 2. If we send a batch of events, the last of which causes, say, a page turn, and invokes flushUnreportedEvents(), we will never get the ack that the batch made it to the server
* so we just clear the queue and assume that they made it. During empirical testing, events did continue to get sent event after the browser is closed as long as there is a network connection.
* 3. If the ingestion server is down, we would only retry as long as the session is open, and lose all events once the user leaves. Events are usually flushed on page turns
* without the opportunity to see if the send was successful (see 2 above) so if we wanted to preserve events in the case of ingestion server failure,
* we would have to a) keep track of the previous send attempts, b) not flush events on page turn, c) stash the events and the retry state in persistent storage,
* and d) fetch the events from persistent storage and restore the retry state, which we choose not to do in order to avoid all of this complexity for what is probably a rare scenario.
*
* Note: each topic has its own queue, and all of the above logic applies to each individual queue.
* For example, exponential backoff works independently on a per-topic basis, in case the server tells us to back off of one topic, but not another.
* Testing tips:
* 1) A debug message is logged every time a postInterval timer is triggered, but the metricskit logger debug messages are off by default.
* They can be enabled in Web inspector via: metrics.system.logger.setLevel(metrics.system.logger.DEBUG);
* 2) Exponential backoff can be tested by using a debug source with the 'testExpontentialBackoff' flag enabled.
* When this flag is enabled, the metrics queue will skip sending and instead schedule the next retry for _postFrequency() * RETRY_EXPONENT_BASE ^ n milliseconds
* where n is the current retry attempt. (see mt-metricskit docs for more details on using debug sources)
* To see this in action, you can enable debug logs as in (1) above, then set a debug source with testExponentialBackoff=true (and optionally, a lower postFrequency),
* then call recordEvent() to enqueue an event.
* You should see a debug message (which includes a timestamp) after postFrequency milliseconds, and then every postFrequency * 2^n milliseconds thereafter.
*
* @param {Object} topicConfig - a instance of Config class(mt-client-config) which contains the topic defined the Figaro "topic" that this event should be stored under
* @param {Object} eventFields a JavaScript object which will be converted to a JSON string and enqued for sending to Figaro according to the postFrequency schedule
* @param {Boolean} postNow - effectively forces an immediate send, along with any other messages that may be sitting in the queue
* @returns {Promise}
*/
function recordEvent(topicConfig, eventFields, postNow) {
var topic = topicConfig.topic();
return topicConfig.disabled().then(function (disabled) {
if (!disabled) {
return topicConfig
.value('postFrequency')
.then(function (postFrequency) {
if (postFrequency === 0) {
postNow = true;
}
// The "pagehide" event was tested and works reliably, so we only need to keep the queue in memory, and expect clients to clear the queue on app close
return _eventQueue.enqueueEvent(topicConfig, eventFields).then(function () {
return postFrequency;
});
})
.then(function (postFrequency) {
if (postNow) {
return _eventQueue.sendEvents(CONSTANTS.SEND_METHOD.AJAX, true);
} else if (!_eventQueue.eventQueues[topic].postIntervalToken && _eventQueue.postIntervalEnabled) {
// Schedule the next send if the timer isn't already running
_eventQueue.setTopicPostInterval(topicConfig, postFrequency);
}
});
}
});
}
/**
* Sends any remaining events in the queue, then clears it.
* Events will be sent as individual image pings or as synchronous AJAX requests for iOS (these are the only send methods that actually
* get through during a pagehide event). We expect clients to call this function before the app closes in order to clear the event queues,
* otherwise any remaining events will be lost. We could theoretically add our own event listener so this call happens automatically,
* but single page apps could be using history.pushState which triggers onpagehide, and in those cases they would not
* need to flush until the app is actually closing.
* Note: This is typically called on page / app close when the JS context is about to disappear and thus we will not know if the events made it to the server
* @param {Boolean} appIsExiting - Pass true if events are being flushed due to your app exiting or page going away
* (the send method will be different in order to attempt to post events prior to actual termination)
* @param {String} appExitSendMethod (optional) the send method for how events will be flushed when the app is exiting.
* Possible options are enumerated in the `eventRecorder.SEND_METHOD` object.
* Note: This argument will be ignored if appIsExiting is false.
* @returns {Promise}
*/
function flushUnreportedEvents(appIsExiting, appExitSendMethod) {
if (appIsExiting) {
if (appExitSendMethod === SEND_METHOD.BEACON_SYNCHRONOUS) {
return flushUnreportedEventsSynchronously();
}
if (reflect.isString(appExitSendMethod) && _eventQueue.objectContainsValue(SEND_METHOD, appExitSendMethod)) {
return _eventQueue.sendEvents(appExitSendMethod, true);
} else if (reflect.isFunction(navigator.sendBeacon)) {
return _eventQueue.sendEvents(CONSTANTS.SEND_METHOD.BEACON, true);
} else {
// iOS browsers do not allow image pings to send onpagehide; use (deprecated) synchronous AJAX in those browsers
if (_isIOS()) {
return _eventQueue.sendEvents(CONSTANTS.SEND_METHOD.AJAX_SYNCHRONOUS, true);
} else {
return _eventQueue.sendEvents(CONSTANTS.SEND_METHOD.IMAGE, true);
}
}
} else {
return _eventQueue.sendEvents(CONSTANTS.SEND_METHOD.AJAX, true);
}
}
function flushUnreportedEventsSynchronously() {
for (var topic in _eventQueue.eventQueues) {
var topicQueue = _eventQueue.eventQueues[topic];
var flushConfig = topicQueue.flushConfig;
var resolvedTopicConfig = reflect.extend({}, flushConfig, {
_topic: topic,
topic: function () {
return this._topic;
}
});
_eventQueue.sendEventsViaBeacon(resolvedTopicConfig);
}
}
/*
* src/event_recorder.js
* mt-event-queue
*
* Copyright © 2016-2017 Apple Inc. All rights reserved.
*
*/
/**
* Provides a pre-built delegate to use against the metrics.system.eventRecorder delegate via metrics.system.eventRecorder.setDelegate()
* If you want to use *most* of these methods, but not *all* of them, you can set this delegate and then create your own with whichever few methods you need to
* customize additionally, and then setDelegate() *that* delegate, in order to override those methods.
* @constructor
* @param {Object} kit An object that implements the Kit interface
*/
var QueuedEventRecorder = function QueuedEventRecorder(kit) {
Base.apply(this, arguments);
};
QueuedEventRecorder.prototype = Object.create(Base.prototype);
QueuedEventRecorder.prototype.constructor = QueuedEventRecorder;
/**
************************************ PSEUDO-PRIVATE METHODS/IVARS ************************************
* These functions need to be accessible for ease of testing, but should not be used by clients
*/
QueuedEventRecorder.prototype._utResetQueue = function _utResetQueue() {
for (var topic in _utQueue().eventQueues) {
_utQueue().resetTopicPostInterval(topic);
}
_utQueue().eventQueues = {};
};
/**
* An implementation of _record method in the parent class.
* @param {Object} topicConfig a config instance for the Figaro "topic" to send to
* @param {Object} eventFields a JavaScript object which will be converted to a JSON string and enqued for sending to Figaro according to the postFrequency schedule.
* @param {Boolean} postNow - effectively forces an immediate send, along with any other messages that may be sitting in the queue
* @returns {Promise}
*/
QueuedEventRecorder.prototype._record = function record(topicConfig, eventFields, postNow) {
return recordEvent(topicConfig, eventFields, postNow);
};
/**
************************************ PUBLIC METHODS/IVARS ************************************
*/
QueuedEventRecorder.prototype.SEND_METHOD = SEND_METHOD;
/**
* Allows replacement of one or more of this class' functions
* Any method on the passed-in object which matches a method that this class has will be called instead of the built-in class method.
* To replace *all* methods of his class, simply have your delegate implement all the methods of this class
* Your delegate can be a true object instance, an anonymous object, or a class object.
* Your delegate is free to have as many additional non-matching methods as it likes.
* It can even act as a delegate for multiple MetricsKit objects, though that is not recommended.
*
* "setDelegate()" may be called repeatedly, with the functions in the most-recently set delegates replacing any functions matching those in the earlier delegates, as well as any as-yet unreplaced functions.
* This allows callers to use "canned" delegates to get most of their functionality, but still replace some number of methods that need custom implementations.
* If, for example, a client wants to use the "canned" itml/environment delegate with the exception of, say, the "appVersion" method, they can set itml/environment as the delegate, and
* then call "setDelegate()" again with their own delegate containing only a single method of "appVersion" as the delegate, which would leave all the other "replaced" methods intact,
* but override the "appVersion" method again, this time with their own supplied delegate.
*
* NOTE: The delegate function will have a property called origFunction representing the original function that it replaced.
* This allows the delegate to, essentially, call "super" before or after it does some work.
* If a replaced method is overridden again with a subsequent "setDelegate()" call, the "origFunction" property will be the previous delegate's function.
* @example:
* To override one or more methods, in place:
* eventRecorder.setDelegate({recordEvent: itms.recordEvent});
* To override one or more methods with a separate object:
* eventRecorder.setDelegate(eventRecorderDelegate);
* (where "eventRecorderDelegate" might be defined elsewhere as, e.g.:
* var eventRecorderDelegate = {recordEvent: itms.recordEvent,
* sendMethod: 'itms'};
* To override one or more methods with an instantiated object from a class definition:
* eventRecorder.setDelegate(new EventRecorderDelegate());
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.prototype.recordEvent = itms.recordEvent;
* EventRecorderDelegate.prototype.sendMethod = function sendMethod() {
* return 'itms';
* };
* To override one or more methods with a class object (with "static" methods):
* eventRecorder.setDelegate(EventRecorderDelegate);
* (where "EventRecorderDelegate" might be defined elsewhere as, e.g.:
* function EventRecorderDelegate() {
* }
* EventRecorderDelegate.recordEvent = itms.recordEvent;
* EventRecorderDelegate.sendMethod = function sendMethod() {
* return 'itms';
* };
* @param {Object} Object or Class with delegate method(s) to be called instead of default (built-in) methods.
* @returns {Boolean} true if one or more methods on the delegate object match one or more methods on the default object,
* otherwise returns false.
*/
QueuedEventRecorder.prototype.setDelegate = function setDelegate(delegate) {
return reflect.attachDelegate(this, delegate);
};
/**
* Sends any remaining events in the queue, then clears it
* This is typically called on page / app close when the JS context is about to disappear and thus we will
* not know if the events made it to the server
* @param {Boolean} appIsExiting - Pass true if events are being flushed due to your app exiting or page going away
* (the send method will be different in order to attempt to post events prior to actual termination)
* @param {String} appExitSendMethod (optional) the send method for how events will be flushed when the app is exiting.
* Possible options are enumerated in the `eventRecorder.SEND_METHOD` object.
* Note: This argument will be ignored if appIsExiting is false.
* @returns {Promise}
*/
QueuedEventRecorder.prototype.flushUnreportedEvents = function flushUnreportedEvents$1(appIsExiting, appExitSendMethod) {
return flushUnreportedEvents.apply(null, arguments);
};
/**
* Set event queue related properties for the giving topic
* @param {String} topic defines the Figaro "topic" that this event should be stored under
* @param {Object} properties the event queue properties for the topic
* @param {Boolean} properties.anonymous true if sending all events for the topic with credentials omitted(no cookies, no PII fields)
*/
QueuedEventRecorder.prototype.setProperties = function setProperties(topic, properties) {
Object.getPrototypeOf(QueuedEventRecorder.prototype).setProperties.call(this, topic, properties);
_utQueue().setProperties(topic, properties);
};
/**
* An implementation of cleanup method in the parent class.
*/
QueuedEventRecorder.prototype.cleanup = function cleanup() {
Object.getPrototypeOf(QueuedEventRecorder.prototype).cleanup.call(this);
this._utResetQueue();
};
/*
* src/immediate_event_recorder.js
* mt-event-queue
*
* Copyright © 2016-2019 Apple Inc. All rights reserved.
*
*/
/**
* Provides a pre-built delegate to use against the metrics.system.eventRecorder delegate via metrics.system.eventRecorder.setDelegate()
* If you want to use *most* of these methods, but not *all* of them, you can set this delegate and then create your own with whichever few methods you need to
* customize additionally, and then setDelegate() *that* delegate, in order to override those methods.
* @constructor
* @param {Object} kit An object that implements the Kit interface
*/
var ImmediateEventRecorder = function ImmediateEventRecorder(kit) {
Base.apply(this, arguments);
};
ImmediateEventRecorder.prototype = Object.create(Base.prototype);
ImmediateEventRecorder.prototype.constructor = ImmediateEventRecorder;
/**
************************************ PRIVATE METHODS/IVARS ************************************
*/
/**
* An implementation of _record method in the parent class.
* @param {Object} topicConfig a config instance for the Figaro "topic" to send to
* @param eventFields
* @returns {Promise}
*/
ImmediateEventRecorder.prototype._record = function record(topicConfig, eventFields) {
var jsonEventsString = enrichAndSerializeEvent(eventFields);
if (jsonEventsString) {
return Promise.all([metricsUrlForConfig(topicConfig), requestTimeoutForConfig(topicConfig)]).then(
function (outputs) {
var topicUrl = outputs[0];
var requestTimeout = outputs[1];
var options = { timeout: requestTimeout };
if (
this._topicPropsCache[topicConfig.topic()] &&
this._topicPropsCache[topicConfig.topic()].anonymous
) {
options.withCredentials = false;
}
network.makeAjaxRequest(topicUrl, 'POST', jsonEventsString, null, null, options);
}.bind(this)
);
}
};
/*
* mt-event-queue/index.js
* mt-event-queue
*
* Copyright © 2016-2017 Apple Inc. All rights reserved.
*
*/
var logger = /*#__PURE__*/ loggerNamed('mt-event-queue');
export { QueuedEventRecorder as EventRecorder, ImmediateEventRecorder, environment, logger, network, setPostIntervalEnabled as setEventQueuePostIntervalEnabled };
|