-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathloader.js
More file actions
572 lines (499 loc) · 16.5 KB
/
loader.js
File metadata and controls
572 lines (499 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
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
/*
* This module should handle all of the loading of bundles. Ideally it would work
* offline, so it should be a service worker. We will migrate code from the main
* file to here.
*/
import { utils } from '@adobe/rum-distiller';
const { addCalculatedProps } = utils;
function getPersistentToken() {
return localStorage.getItem('rum-bundler-token');
}
export const DOMAIN_KEY_RESOLVER_URL = 'https://optel-alerts.audvatwork.workers.dev/domain-key';
const INVALID_DOMAIN_DOMAINKEY_MESSAGE = 'Invalid domain/domainkey combination. Please verify and try again.';
export function getResolverSecret(urlSearch = window.location.search) {
const urlParams = new URLSearchParams(urlSearch);
const urlDomainKey = urlParams.get('domainkey');
if (urlDomainKey && urlDomainKey.trim()) {
return {
secret: urlDomainKey.trim(),
source: 'url',
};
}
const token = getPersistentToken();
if (token && token.trim()) {
return {
secret: token.trim(),
source: 'localStorage',
};
}
return {
secret: '',
source: 'none',
};
}
export function normalizeDomainKeyResolverResponse(status, payload, domain, source) {
const possibleDomainKey = payload?.domainKey || payload?.domainkey;
if (status >= 200 && status < 300 && typeof possibleDomainKey === 'string' && possibleDomainKey.trim()) {
return {
ok: true,
domain,
domainKey: possibleDomainKey.trim(),
source,
};
}
return {
ok: false,
domain,
source,
status,
error: {
code: payload?.code || 'INVALID_DOMAIN_DOMAINKEY',
message: payload?.message || INVALID_DOMAIN_DOMAINKEY_MESSAGE,
userMessage: INVALID_DOMAIN_DOMAINKEY_MESSAGE,
},
};
}
export async function fetchDomainKey(domain) {
try {
const { secret, source } = getResolverSecret();
const resolverResp = await fetch(DOMAIN_KEY_RESOLVER_URL, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({
domain,
secret,
}),
});
let payload = null;
try {
payload = await resolverResp.json();
} catch (e) {
payload = null;
}
return normalizeDomainKeyResolverResponse(
resolverResp.status,
payload,
domain,
source,
);
} catch (e) {
return {
ok: false,
domain,
source: 'unknown',
status: 0,
error: {
code: 'RESOLVER_UNREACHABLE',
message: e?.message || INVALID_DOMAIN_DOMAINKEY_MESSAGE,
userMessage: INVALID_DOMAIN_DOMAINKEY_MESSAGE,
},
};
}
}
export default class DataLoader {
constructor() {
this.cache = new Map();
this.API_ENDPOINT = 'https://bundles.aem.page';
this.DOMAIN = 'www.thinktanked.org';
this.DOMAIN_KEY = undefined;
this.ORG = undefined;
this.SCOPE = undefined; // unused
this.granularity = 'month';
this.cacheExpiration = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
this.useCache = false; // enable/disable IndexedDB caching
this.DB_NAME = 'rum-bundles-db';
this.DB_VERSION = 1;
this.STORE_NAME = 'bundles-cache';
this.dbPromise = null;
this.dbInitialized = false;
}
/**
* Initializes the IndexedDB database
* @returns {Promise<IDBDatabase>} - Promise resolving to the database instance
*/
async initDB() {
if (this.dbPromise) {
return this.dbPromise;
}
this.dbPromise = new Promise((resolve, reject) => {
if (!window.indexedDB) {
console.warn('IndexedDB is not supported in this browser');
reject(new Error('IndexedDB not supported'));
return;
}
const request = indexedDB.open(this.DB_NAME, this.DB_VERSION);
request.onerror = () => {
console.error('Failed to open IndexedDB:', request.error);
reject(request.error);
};
request.onsuccess = () => {
this.dbInitialized = true;
resolve(request.result);
};
request.onupgradeneeded = (event) => {
const db = event.target.result;
// Create object store if it doesn't exist
if (!db.objectStoreNames.contains(this.STORE_NAME)) {
const objectStore = db.createObjectStore(this.STORE_NAME, { keyPath: 'url' });
// Create index on timestamp for efficient cleanup of expired entries
objectStore.createIndex('timestamp', 'timestamp', { unique: false });
}
};
});
return this.dbPromise;
}
async flush() {
this.cache.clear();
await this.clearCache();
}
/**
* Clears all cached entries from IndexedDB
*/
async clearCache() {
try {
const db = await this.initDB();
const transaction = db.transaction([this.STORE_NAME], 'readwrite');
const objectStore = transaction.objectStore(this.STORE_NAME);
objectStore.clear();
return new Promise((resolve, reject) => {
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error);
});
} catch (e) {
console.warn('Failed to clear IndexedDB cache:', e);
}
}
/**
* Removes expired entries from the cache
*/
async cleanupExpiredCache() {
try {
const db = await this.initDB();
const transaction = db.transaction([this.STORE_NAME], 'readwrite');
const objectStore = transaction.objectStore(this.STORE_NAME);
const index = objectStore.index('timestamp');
const now = Date.now();
const expiredThreshold = now - this.cacheExpiration;
const request = index.openCursor();
request.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
if (cursor.value.timestamp < expiredThreshold) {
cursor.delete();
}
cursor.continue();
}
};
} catch (e) {
console.warn('Failed to cleanup expired cache:', e);
}
}
/**
* Retrieves cached data from IndexedDB if available and not expired
* @param {string} url - The API URL used as cache key
* @returns {Promise<object|null>} - Cached data or null if not found/expired
*/
async getCachedData(url) {
if (!this.useCache) {
return null;
}
try {
const db = await this.initDB();
const transaction = db.transaction([this.STORE_NAME], 'readonly');
const objectStore = transaction.objectStore(this.STORE_NAME);
const request = objectStore.get(url);
return new Promise((resolve, _reject) => {
request.onsuccess = () => {
const result = request.result;
if (!result) {
resolve(null);
return;
}
const now = Date.now();
// Check if cache has expired
if (now - result.timestamp > this.cacheExpiration) {
// Delete expired entry
this.deleteCachedData(url);
resolve(null);
return;
}
resolve(result.data);
};
request.onerror = () => {
console.warn('Failed to retrieve cached data:', request.error);
resolve(null);
};
});
} catch (e) {
console.warn('Failed to access IndexedDB:', e);
return null;
}
}
/**
* Stores data in IndexedDB with current timestamp
* @param {string} url - The API URL used as cache key
* @param {object} data - The data to cache
*/
async setCachedData(url, data) {
if (!this.useCache) {
return;
}
try {
const db = await this.initDB();
const transaction = db.transaction([this.STORE_NAME], 'readwrite');
const objectStore = transaction.objectStore(this.STORE_NAME);
const cacheItem = {
url,
data,
timestamp: Date.now(),
};
const request = objectStore.put(cacheItem);
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve();
request.onerror = () => {
console.warn('Failed to cache data:', request.error);
// If quota exceeded, try to cleanup old entries
if (request.error.name === 'QuotaExceededError') {
this.cleanupExpiredCache().then(() => {
// Retry after cleanup
objectStore.put(cacheItem);
});
}
reject(request.error);
};
});
} catch (e) {
console.warn('Failed to cache data:', e);
}
}
/**
* Deletes a specific cached entry
* @param {string} url - The API URL to delete from cache
*/
async deleteCachedData(url) {
try {
const db = await this.initDB();
const transaction = db.transaction([this.STORE_NAME], 'readwrite');
const objectStore = transaction.objectStore(this.STORE_NAME);
objectStore.delete(url);
} catch (e) {
console.warn('Failed to delete cached data:', e);
}
}
set domainKey(key) {
this.DOMAIN_KEY = key;
}
get domain() {
return this.DOMAIN;
}
set domain(domain) {
this.DOMAIN = domain;
}
set apiEndpoint(endpoint) {
this.API_ENDPOINT = endpoint;
}
apiURL(datePath, hour) {
const u = new URL(this.API_ENDPOINT);
u.pathname = [
'bundles',
this.DOMAIN,
datePath,
hour,
]
.filter((p) => !!p) // remove empty strings
.join('/');
u.searchParams.set('domainkey', this.DOMAIN_KEY);
return u.toString();
}
// eslint-disable-next-line class-methods-use-this
filterByDateRange(data, start, end) {
if (start || end) {
const filtered = data.filter((bundle) => {
const time = new Date(bundle.timeSlot);
return ((start ? time >= start : true) && (end ? time <= end : true));
});
return filtered;
}
return data;
}
async fetchUTCMonth(utcISOString, start, end) {
this.granularity = 'month';
const [date] = utcISOString.split('T');
const dateSplits = date.split('-');
dateSplits.pop();
const monthPath = dateSplits.join('/');
if (this.DOMAIN_KEY === undefined) {
return {date, rumBundles: []};
}
const apiRequestURL = this.apiURL(monthPath);
// Check cache first
const cachedData = await this.getCachedData(apiRequestURL);
if (cachedData) {
return { date, rumBundles: this.filterByDateRange(cachedData.rumBundles, start, end) };
}
// Fetch from API if not cached
const resp = await fetch(apiRequestURL);
const json = await resp.json();
const { rumBundles } = json;
rumBundles.forEach((bundle) => addCalculatedProps(bundle));
// Store in cache (don't await to avoid blocking)
// this.setCachedData(apiRequestURL, { rumBundles });
return { date, rumBundles: this.filterByDateRange(rumBundles, start, end) };
}
async fetchUTCDay(utcISOString, start, end) {
this.granularity = 'day';
const [date] = utcISOString.split('T');
const datePath = date.split('-').join('/');
const apiRequestURL = this.apiURL(datePath);
if (this.DOMAIN_KEY === undefined) {
return {date, rumBundles: []};
}
// Check cache first
const cachedData = await this.getCachedData(apiRequestURL);
if (cachedData) {
return { date, rumBundles: this.filterByDateRange(cachedData.rumBundles, start, end) };
}
// Fetch from API if not cached
const resp = await fetch(apiRequestURL);
const json = await resp.json();
const { rumBundles } = json;
rumBundles.forEach((bundle) => addCalculatedProps(bundle));
// Store in cache (don't await to avoid blocking)
// this.setCachedData(apiRequestURL, { rumBundles });
return { date, rumBundles: this.filterByDateRange(rumBundles, start, end) };
}
async fetchUTCHour(utcISOString, start, end) {
this.granularity = 'hour';
const [date, time] = utcISOString.split('T');
const datePath = date.split('-').join('/');
const hour = time.split(':')[0];
const apiRequestURL = this.apiURL(datePath, hour);
if (this.DOMAIN_KEY === undefined) {
return {date, hour, rumBundles: []};
}
// Check cache first
const cachedData = await this.getCachedData(apiRequestURL);
if (cachedData) {
return { date, hour, rumBundles: this.filterByDateRange(cachedData.rumBundles, start, end) };
}
// Fetch from API if not cached
const resp = await fetch(apiRequestURL);
const json = await resp.json();
const { rumBundles } = json;
rumBundles.forEach((bundle) => addCalculatedProps(bundle));
// do not cache if the date is today
if (date !== new Date().toISOString().split('T')[0]) {
// Store in cache (don't await to avoid blocking)
// this.setCachedData(apiRequestURL, { rumBundles });
}
return { date, hour, rumBundles: this.filterByDateRange(rumBundles, start, end) };
}
async fetchLastWeek(endDate) {
const date = endDate ? new Date(endDate) : new Date();
const hoursInWeek = 7 * 24;
const promises = [];
for (let i = 0; i < hoursInWeek; i += 1) {
promises.push(this.fetchUTCHour(date.toISOString()));
date.setTime(date.getTime() - (3600 * 1000));
}
const chunks = Promise.all(promises);
return chunks;
}
async fetchPrevious31Days(endDate) {
const date = endDate ? new Date(endDate) : new Date();
const days = 31;
const promises = [];
for (let i = 0; i < days; i += 1) {
promises.push(this.fetchUTCDay(date.toISOString()));
date.setDate(date.getDate() - 1);
}
const chunks = Promise.all(promises);
return chunks;
}
async fetchPrevious12Months(endDate) {
const date = endDate ? new Date(endDate) : new Date();
const months = 13; // 13 to include 2 partial months (first and last)
const promises = [];
for (let i = 0; i < months; i += 1) {
promises.push(this.fetchUTCMonth(date.toISOString()));
date.setMonth(date.getMonth() - 1);
}
const chunks = Promise.all(promises);
return chunks;
}
async fetchDateRange(startDate, endDate = new Date().toISOString()) {
const start = new Date(startDate);
const end = new Date(endDate);
const hoursInRange = Math.floor((end - start) / (1000 * 60 * 60));
const daysInRange = Math.floor((end - start) / (1000 * 60 * 60 * 24));
const monthsInRange = Math.floor((end - start) / (1000 * 60 * 60 * 24 * 30));
let promises = [];
if (daysInRange < 0) {
throw new Error('Start date must be before end date');
} else if (hoursInRange < 200) {
// fetch each hour
promises = Array.from({ length: hoursInRange + 1 }, (_, i) => {
const date = new Date(start);
date.setHours(date.getHours() + i + 1);
return date.toISOString();
}).map((hour) => this.fetchUTCHour(hour));
} else if (daysInRange < 200) {
// fetch each day
promises = Array.from({ length: daysInRange + 1 }, (_, i) => {
const date = new Date(start);
date.setDate(date.getDate() + i + 1);
return date.toISOString();
}).map((day) => this.fetchUTCDay(day));
} else {
// fetch each month
promises = Array.from({ length: monthsInRange + 1 }, (_, i) => {
const date = new Date(start);
date.setMonth(date.getMonth() + i + 1);
return date.toISOString();
}).map((month) => this.fetchUTCMonth(month));
}
return Promise.all(promises);
}
async fetchPeriod(startDate, endDate) {
const start = new Date(startDate);
const originalStart = new Date(start);
let end = endDate ? new Date(endDate) : new Date();
if (end > Date.now()) {
end = new Date();
}
const diff = end.getTime() - start.getTime();
if (diff < 0) {
throw new Error('Start date must be before end date');
}
const promises = [];
if (diff <= (1000 * 60 * 60 * 24 * 7)) {
// less than a week
const hours = Math.round((diff / (1000 * 60 * 60))) + 1;
for (let i = 0; i < hours; i += 1) {
promises.push(this.fetchUTCHour(start.toISOString(), originalStart, end));
if (start.getHours() >= 23) {
start.setDate(start.getDate() + 1);
start.setHours(0);
} else {
start.setHours(start.getHours() + 1);
}
}
} else if (diff <= (1000 * 60 * 60 * 24 * 31)) {
// less than a month
const days = Math.round((diff / (1000 * 60 * 60 * 24))) + 1;
for (let i = 0; i < days; i += 1) {
promises.push(this.fetchUTCDay(start.toISOString(), originalStart, end));
start.setDate(start.getDate() + 1);
}
} else {
const months = Math.round(diff / (1000 * 60 * 60 * 24 * 31)) + 1;
for (let i = 0; i < months; i += 1) {
promises.push(this.fetchUTCMonth(start.toISOString(), originalStart, end));
start.setMonth(start.getMonth() + 1);
}
}
return Promise.all(promises);
}
}