@mparticle/web-sdk 2.18.3 → 2.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mparticle/web-sdk",
3
- "version": "2.18.3",
3
+ "version": "2.19.1",
4
4
  "description": "mParticle core SDK for web applications",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
package/src/apiClient.ts CHANGED
@@ -189,7 +189,7 @@ export default function APIClient(
189
189
  );
190
190
  xhr.send(
191
191
  JSON.stringify(
192
- mpInstance._ServerModel.convertEventToDTO(
192
+ mpInstance._ServerModel.convertEventToV2DTO(
193
193
  event as IUploadObject
194
194
  )
195
195
  )
@@ -9,17 +9,35 @@ import { convertEvents } from './sdkToEventsApiConverter';
9
9
  import Types from './types';
10
10
  import { isEmpty } from './utils';
11
11
 
12
+ /**
13
+ * BatchUploader contains all the logic to upload batches to mParticle.
14
+ * It queues events as they come in and at set intervals turns them into batches.
15
+ * It then attempts to upload them to mParticle.
16
+ *
17
+ * These uploads happen on an interval basis using window.fetch or XHR
18
+ * requests, depending on what is available in the browser.
19
+ *
20
+ * Uploads can also be triggered on browser visibility/focus changes via an
21
+ * event listener, which then uploads to mPartice via the browser's Beacon API.
22
+ */
23
+
12
24
  export class BatchUploader {
13
- //we upload JSON, but this content type is required to avoid a CORS preflight request
25
+ // We upload JSON, but this content type is required to avoid a CORS preflight request
14
26
  static readonly CONTENT_TYPE: string = 'text/plain;charset=UTF-8';
15
27
  static readonly MINIMUM_INTERVAL_MILLIS: number = 500;
16
28
  uploadIntervalMillis: number;
17
- pendingEvents: SDKEvent[];
18
- pendingUploads: Batch[];
29
+ eventsQueuedForProcessing: SDKEvent[];
30
+ batchesQueuedForProcessing: Batch[];
19
31
  mpInstance: MParticleWebSDK;
20
32
  uploadUrl: string;
21
33
  batchingEnabled: boolean;
34
+ private uploader: AsyncUploader;
22
35
 
36
+ /**
37
+ * Creates an instance of a BatchUploader
38
+ * @param {MParticleWebSDK} mpInstance - the mParticle SDK instance
39
+ * @param {number} uploadInterval - the desired upload interval in milliseconds
40
+ */
23
41
  constructor(mpInstance: MParticleWebSDK, uploadInterval: number) {
24
42
  this.mpInstance = mpInstance;
25
43
  this.uploadIntervalMillis = uploadInterval;
@@ -28,8 +46,8 @@ export class BatchUploader {
28
46
  if (this.uploadIntervalMillis < BatchUploader.MINIMUM_INTERVAL_MILLIS) {
29
47
  this.uploadIntervalMillis = BatchUploader.MINIMUM_INTERVAL_MILLIS;
30
48
  }
31
- this.pendingEvents = [];
32
- this.pendingUploads = [];
49
+ this.eventsQueuedForProcessing = [];
50
+ this.batchesQueuedForProcessing = [];
33
51
 
34
52
  const { SDKConfig, devToken } = this.mpInstance._Store;
35
53
  const baseUrl = this.mpInstance._Helpers.createServiceUrl(
@@ -38,15 +56,20 @@ export class BatchUploader {
38
56
  );
39
57
  this.uploadUrl = `${baseUrl}/events`;
40
58
 
41
- setTimeout(() => {
42
- this.prepareAndUpload(true, false);
43
- }, this.uploadIntervalMillis);
59
+ this.uploader = window.fetch
60
+ ? new FetchUploader(this.uploadUrl)
61
+ : new XHRUploader(this.uploadUrl);
62
+
63
+ this.triggerUploadInterval(true, false);
44
64
  this.addEventListeners();
45
65
  }
46
66
 
67
+ // Adds listeners to be used trigger Navigator.sendBeacon if the browser
68
+ // loses focus for any reason, such as closing browser tab or minimizing window
47
69
  private addEventListeners() {
48
70
  const _this = this;
49
71
 
72
+ // visibility change is a document property, not window
50
73
  document.addEventListener('visibilitychange', () => {
51
74
  _this.prepareAndUpload(false, _this.isBeaconAvailable());
52
75
  });
@@ -65,16 +88,32 @@ export class BatchUploader {
65
88
  return false;
66
89
  }
67
90
 
91
+ // Triggers a setTimeout for prepareAndUpload
92
+ private triggerUploadInterval(
93
+ triggerFuture: boolean = false,
94
+ useBeacon: boolean = false
95
+ ): void {
96
+ setTimeout(() => {
97
+ this.prepareAndUpload(triggerFuture, useBeacon);
98
+ }, this.uploadIntervalMillis);
99
+ }
100
+
101
+ /**
102
+ * This method will queue a single Event which will eventually be processed into a Batch
103
+ * @param event event that should be queued
104
+ */
68
105
  queueEvent(event: SDKEvent): void {
69
106
  if (!isEmpty(event)) {
70
- this.pendingEvents.push(event);
107
+ this.eventsQueuedForProcessing.push(event);
71
108
  this.mpInstance.Logger.verbose(
72
109
  `Queuing event: ${JSON.stringify(event)}`
73
110
  );
74
111
  this.mpInstance.Logger.verbose(
75
- `Queued event count: ${this.pendingEvents.length}`
112
+ `Queued event count: ${this.eventsQueuedForProcessing.length}`
76
113
  );
77
114
 
115
+ // TODO: Remove this check once the v2 code path is removed
116
+ // https://go.mparticle.com/work/SQDSDKS-3720
78
117
  if (
79
118
  !this.batchingEnabled ||
80
119
  Types.TriggerUploadType[event.EventDataType]
@@ -93,7 +132,7 @@ export class BatchUploader {
93
132
  * @param sdkEvents current pending events
94
133
  * @param defaultUser the user to reference for events that are missing data
95
134
  */
96
- private static createNewUploads(
135
+ private static createNewBatches(
97
136
  sdkEvents: SDKEvent[],
98
137
  defaultUser: MParticleUser,
99
138
  mpInstance: MParticleWebSDK
@@ -141,9 +180,8 @@ export class BatchUploader {
141
180
  mpInstance._Store.SDKConfig.onCreateBatch;
142
181
 
143
182
  if (onCreateBatchCallback) {
144
- uploadBatchObject = onCreateBatchCallback(
145
- uploadBatchObject
146
- );
183
+ uploadBatchObject =
184
+ onCreateBatchCallback(uploadBatchObject);
147
185
  if (uploadBatchObject) {
148
186
  uploadBatchObject.modified = true;
149
187
  } else {
@@ -169,112 +207,122 @@ export class BatchUploader {
169
207
  * @param triggerFuture whether to trigger the loop again - for manual/forced uploads this should be false
170
208
  * @param useBeacon whether to use the beacon API - used when the page is being unloaded
171
209
  */
172
- private async prepareAndUpload(triggerFuture: boolean, useBeacon: boolean) {
210
+ private async prepareAndUpload(
211
+ triggerFuture: boolean,
212
+ useBeacon: boolean
213
+ ): Promise<void> {
173
214
  const currentUser = this.mpInstance.Identity.getCurrentUser();
174
215
 
175
- const currentEvents = this.pendingEvents;
176
- this.pendingEvents = [];
177
- const newUploads = BatchUploader.createNewUploads(
216
+ const currentEvents = this.eventsQueuedForProcessing;
217
+ this.eventsQueuedForProcessing = [];
218
+
219
+ const newBatches = BatchUploader.createNewBatches(
178
220
  currentEvents,
179
221
  currentUser,
180
222
  this.mpInstance
181
223
  );
182
- if (newUploads && newUploads.length) {
183
- this.pendingUploads.push(...newUploads);
224
+ if (!isEmpty(newBatches)) {
225
+ this.batchesQueuedForProcessing.push(...newBatches);
184
226
  }
185
227
 
186
- const currentUploads = this.pendingUploads;
187
- this.pendingUploads = [];
188
- const remainingUploads: Batch[] = await this.upload(
189
- this.mpInstance.Logger,
190
- currentUploads,
191
- useBeacon
192
- );
193
- if (remainingUploads && remainingUploads.length) {
194
- this.pendingUploads.unshift(...remainingUploads);
228
+ const batchesToUpload = this.batchesQueuedForProcessing;
229
+ const batchesThatDidNotUpload: Batch[] = [];
230
+ this.batchesQueuedForProcessing = [];
231
+
232
+ // Create an array of promises as we try to upload each batch indvidually
233
+ const promises: Promise<Batch>[] = batchesToUpload.map((upload) => {
234
+ return this.upload(this.mpInstance.Logger, upload, useBeacon);
235
+ });
236
+
237
+ // Iterate through fulfilled promises and store any remaining batches
238
+ // for future re-transmission attempts
239
+ if (!isEmpty(promises)) {
240
+ Promise.all(promises)
241
+ .then((batchResponses) => {
242
+ batchResponses.forEach((batch) =>
243
+ !isEmpty(batch)
244
+ ? batchesThatDidNotUpload.push(batch)
245
+ : null
246
+ );
247
+ })
248
+ .catch((error) => {
249
+ this.mpInstance.Logger.error(
250
+ `Error processing batches during upload attempt: ${error}`
251
+ );
252
+ })
253
+ .finally(() => {
254
+ // Any batches that did not upload should be put back into the queue for processing
255
+ if (!isEmpty(batchesThatDidNotUpload)) {
256
+ this.batchesQueuedForProcessing.unshift(
257
+ ...batchesThatDidNotUpload
258
+ );
259
+ }
260
+ });
195
261
  }
196
262
 
197
263
  if (triggerFuture) {
198
- setTimeout(() => {
199
- this.prepareAndUpload(true, false);
200
- }, this.uploadIntervalMillis);
264
+ this.triggerUploadInterval(triggerFuture, false);
201
265
  }
202
266
  }
203
267
 
204
268
  private async upload(
205
269
  logger: SDKLoggerApi,
206
- _uploads: Batch[],
270
+ batch: Batch,
207
271
  useBeacon: boolean
208
- ): Promise<Batch[]> {
209
- let uploader;
210
-
211
- // Filter out any batches that don't have events
212
- const uploads = _uploads.filter(upload => !isEmpty(upload.events));
213
-
214
- if (isEmpty(uploads)) {
272
+ ): Promise<Batch | null> {
273
+ if (isEmpty(batch) || isEmpty(batch.events)) {
215
274
  return null;
216
275
  }
217
276
 
218
- logger.verbose(`Uploading batches: ${JSON.stringify(uploads)}`);
219
- logger.verbose(`Batch count: ${uploads.length}`);
220
-
221
- for (let i = 0; i < uploads.length; i++) {
222
- const fetchPayload: fetchPayload = {
223
- method: 'POST',
224
- headers: {
225
- Accept: BatchUploader.CONTENT_TYPE,
226
- 'Content-Type': 'text/plain;charset=UTF-8',
227
- },
228
- body: JSON.stringify(uploads[i]),
229
- };
277
+ logger.verbose(`Uploading batches: ${JSON.stringify(batch)}`);
278
+
279
+ const fetchPayload: fetchPayload = {
280
+ method: 'POST',
281
+ headers: {
282
+ Accept: BatchUploader.CONTENT_TYPE,
283
+ 'Content-Type': 'text/plain;charset=UTF-8',
284
+ },
285
+ body: JSON.stringify(batch),
286
+ };
287
+
288
+ // TODO: Make beacon its own function
289
+ // beacon is only used on onbeforeunload onpagehide events
290
+ if (useBeacon && this.isBeaconAvailable()) {
291
+ let blob = new Blob([fetchPayload.body], {
292
+ type: 'text/plain;charset=UTF-8',
293
+ });
294
+ navigator.sendBeacon(this.uploadUrl, blob);
295
+ } else {
296
+ try {
297
+ const response = await this.uploader.upload(fetchPayload);
298
+
299
+ // TODO: Should we make this a switch statement instead?
300
+ if (response.status >= 200 && response.status < 300) {
301
+ logger.verbose(
302
+ `Upload success for request ID: ${batch.source_request_id}`
303
+ );
230
304
 
231
- // beacon is only used on onbeforeunload onpagehide events
232
- if (useBeacon && this.isBeaconAvailable()) {
233
- let blob = new Blob([fetchPayload.body], {
234
- type: 'text/plain;charset=UTF-8',
235
- });
236
- navigator.sendBeacon(this.uploadUrl, blob);
237
- } else {
238
- if (!uploader) {
239
- if (window.fetch) {
240
- uploader = new FetchUploader(this.uploadUrl, logger);
241
- } else {
242
- uploader = new XHRUploader(this.uploadUrl, logger);
243
- }
244
- }
245
- try {
246
- const response = await uploader.upload(
247
- fetchPayload,
248
- uploads,
249
- i
305
+ return null;
306
+ } else if (response.status >= 500 || response.status === 429) {
307
+ logger.error(
308
+ `HTTP error status ${response.status} received`
250
309
  );
251
310
 
252
- if (response.status >= 200 && response.status < 300) {
253
- logger.verbose(
254
- `Upload success for request ID: ${uploads[i].source_request_id}`
255
- );
256
- } else if (
257
- response.status >= 500 ||
258
- response.status === 429
259
- ) {
260
- logger.error(
261
- `HTTP error status ${response.status} received`
262
- );
263
- //server error, add back current events and try again later
264
- return uploads.slice(i, uploads.length);
265
- } else if (response.status >= 401) {
266
- logger.error(
267
- `HTTP error status ${response.status} while uploading - please verify your API key.`
268
- );
269
- //if we're getting a 401, assume we'll keep getting a 401 and clear the uploads.
270
- return null;
271
- }
272
- } catch (e) {
311
+ // Server error, return current batch and try again later
312
+ return batch;
313
+ } else if (response.status >= 401) {
273
314
  logger.error(
274
- `Error sending event to mParticle servers. ${e}`
315
+ `HTTP error status ${response.status} while uploading - please verify your API key.`
275
316
  );
276
- return uploads.slice(i, uploads.length);
317
+ // if we're getting a 401, assume we'll keep getting a 401
318
+ // so return the upload so it can be stored for later use
319
+ return batch;
277
320
  }
321
+ } catch (error) {
322
+ logger.error(
323
+ `Error sending event to mParticle servers. ${error}`
324
+ );
325
+ return batch;
278
326
  }
279
327
  }
280
328
  return null;
@@ -283,34 +331,24 @@ export class BatchUploader {
283
331
 
284
332
  abstract class AsyncUploader {
285
333
  url: string;
286
- logger: SDKLoggerApi;
334
+ public abstract upload(fetchPayload: fetchPayload): Promise<XHRResponse>;
287
335
 
288
- constructor(url: string, logger: SDKLoggerApi) {
336
+ constructor(url: string) {
289
337
  this.url = url;
290
- this.logger = logger;
291
338
  }
292
339
  }
293
340
 
294
341
  class FetchUploader extends AsyncUploader {
295
- private async upload(
296
- fetchPayload: fetchPayload,
297
- uploads: Batch[],
298
- i: number
299
- ) {
342
+ public async upload(fetchPayload: fetchPayload): Promise<XHRResponse> {
300
343
  const response: XHRResponse = await fetch(this.url, fetchPayload);
301
344
  return response;
302
345
  }
303
346
  }
304
347
 
305
348
  class XHRUploader extends AsyncUploader {
306
- private async upload(
307
- fetchPayload: fetchPayload,
308
- uploads: Batch[],
309
- i: number
310
- ) {
349
+ public async upload(fetchPayload: fetchPayload): Promise<XHRResponse> {
311
350
  const response: XHRResponse = await this.makeRequest(
312
351
  this.url,
313
- this.logger,
314
352
  fetchPayload.body
315
353
  );
316
354
  return response;
@@ -318,7 +356,6 @@ class XHRUploader extends AsyncUploader {
318
356
 
319
357
  private async makeRequest(
320
358
  url: string,
321
- logger: SDKLoggerApi,
322
359
  data: string
323
360
  ): Promise<XMLHttpRequest> {
324
361
  const xhr: XMLHttpRequest = new XMLHttpRequest();