@whotracksme/reporting 5.1.28 → 5.1.30

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/package.json +1 -1
  3. package/reporting/example/index.js +2 -12
  4. package/reporting/example/manifests/chromium.json +1 -0
  5. package/reporting/snapshots/0001/events.log.br +0 -0
  6. package/reporting/snapshots/0001/snapshot.json +4173 -0
  7. package/reporting/snapshots/0002/events.log.br +0 -0
  8. package/reporting/snapshots/0002/snapshot.json +2539 -0
  9. package/reporting/snapshots/0003/events.log.br +0 -0
  10. package/reporting/snapshots/0003/snapshot.json +855 -0
  11. package/reporting/snapshots/0004/events.log.br +0 -0
  12. package/reporting/snapshots/0004/snapshot.json +802 -0
  13. package/reporting/src/hash-detector.js +1 -1
  14. package/reporting/src/index.js +1 -2
  15. package/reporting/src/request/config.js +9 -4
  16. package/reporting/src/request/{hash.js → hash/index.js} +3 -3
  17. package/reporting/src/request/index.js +447 -496
  18. package/reporting/src/{webrequest-pipeline → request}/page-store.js +65 -75
  19. package/reporting/src/request/qs-whitelist2.js +0 -2
  20. package/reporting/src/request/steps/cookie-context.js +6 -5
  21. package/reporting/src/request/steps/oauth-detector.js +3 -24
  22. package/reporting/src/request/steps/page-logger.js +3 -4
  23. package/reporting/src/request/steps/token-checker/token-domain.js +1 -1
  24. package/reporting/src/request/steps/token-examiner.js +3 -4
  25. package/reporting/src/request/steps/token-telemetry/cached-entry-pipeline.js +55 -75
  26. package/reporting/src/request/steps/token-telemetry/index.js +86 -115
  27. package/reporting/src/request/steps/token-telemetry/key-pipeline.js +3 -2
  28. package/reporting/src/request/steps/token-telemetry/token-pipeline.js +3 -2
  29. package/reporting/src/request/utils/temp-set.js +2 -4
  30. package/reporting/src/request/{time.js → utils/time.js} +0 -5
  31. package/reporting/src/request/utils/tlds.js +1 -11
  32. package/reporting/src/request/{utils.js → utils/utils.js} +9 -0
  33. package/reporting/src/{webrequest-pipeline/webrequest-context.js → request/utils/webrequest.js} +84 -4
  34. package/reporting/src/utils/url.js +0 -25
  35. package/reporting/test/helpers/scenarios.js +76 -17
  36. package/reporting/test/index.js +3 -8
  37. package/reporting/test/request/database.test.js +96 -0
  38. package/reporting/test/request/{hash.spec.js → hash/index.spec.js} +2 -2
  39. package/reporting/test/request/index.spec.js +24 -46
  40. package/reporting/test/{request-reporter.test.js → request/index.test.js} +102 -46
  41. package/reporting/test/{webrequest-pipeline → request}/page-store.test.js +1 -1
  42. package/reporting/test/request/steps/oauth-detector.spec.js +15 -25
  43. package/reporting/test/request/{utils.spec.js → utils/utils.spec.js} +2 -2
  44. package/reporting/test/setup.unit.js +1 -0
  45. package/reporting/test/utils/url.spec.js +1 -26
  46. package/reporting/src/request/page-telemetry.js +0 -42
  47. package/reporting/src/request/steps/subdomain-check.js +0 -34
  48. package/reporting/src/request/utils/subject.js +0 -37
  49. package/reporting/src/request-reporter.js +0 -111
  50. package/reporting/src/utils/pacemaker.js +0 -279
  51. package/reporting/src/webrequest-pipeline/cname-uncloak.js +0 -110
  52. package/reporting/src/webrequest-pipeline/index.js +0 -286
  53. package/reporting/src/webrequest-pipeline/logger.js +0 -14
  54. package/reporting/src/webrequest-pipeline/pipeline.js +0 -249
  55. package/reporting/src/webrequest-pipeline/utils/webrequest.js +0 -119
  56. package/reporting/test/utils/pacemaker.spec.js +0 -222
  57. package/reporting/test/webrequest-pipeline/index.test.js +0 -160
  58. package/reporting/test/webrequest-pipeline/pipeline.spec.js +0 -251
  59. /package/reporting/src/request/{resources → hash}/prob.js +0 -0
@@ -9,7 +9,7 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
- import ChromeStorageMap from '../request/utils/chrome-storage-map.js';
12
+ import ChromeStorageMap from './utils/chrome-storage-map.js';
13
13
 
14
14
  const PAGE_TTL = 1000 * 60 * 60; // 1 hour
15
15
 
@@ -20,43 +20,40 @@ const PAGE_LOADING_STATE = {
20
20
  COMPLETE: 'complete',
21
21
  };
22
22
 
23
- class Page {
24
- constructor(page) {
25
- this.id = page.id;
26
- this.url = page.url;
27
- this.isPrivate = page.incognito || false;
28
- this.isPrivateServer = page.isPrivateServer || false;
29
- this.created = page.created || Date.now();
30
- this.destroyed = page.destroyed || null;
31
- this.frames = page.frames || {
32
- 0: {
33
- parentFrameId: -1,
34
- url: page.url,
35
- },
36
- };
37
- this.state = page.state || PAGE_LOADING_STATE.CREATED;
38
-
39
- this.activeTime = page.activeTime || 0;
40
- this.activeFrom = page.active ? Date.now() : 0;
41
-
42
- this.requestStats = page.requestStats || {};
43
- this.annotations = page.annotations || {};
44
- this.counter = page.counter || 0;
45
- this.previous = page.previous;
23
+ function makePageActive(page, active) {
24
+ if (active && page.activeFrom === 0) {
25
+ page.activeFrom = Date.now();
26
+ } else if (!active && page.activeFrom > 0) {
27
+ page.activeTime += Date.now() - page.activeFrom;
28
+ page.activeFrom = 0;
46
29
  }
30
+ }
47
31
 
48
- setActive(active) {
49
- if (active && this.activeFrom === 0) {
50
- this.activeFrom = Date.now();
51
- } else if (!active && this.activeFrom > 0) {
52
- this.activeTime += Date.now() - this.activeFrom;
53
- this.activeFrom = 0;
54
- }
55
- }
32
+ function createPageFromTab(tab) {
33
+ const { id, active, url, incognito, created } = tab;
34
+ const page = {};
35
+ page.id = id;
36
+ page.url = url;
37
+ page.isPrivate = incognito || false;
38
+ page.isPrivateServer = false;
39
+ page.created = created || Date.now();
40
+ page.destroyed = null;
41
+ page.frames = {
42
+ 0: {
43
+ parentFrameId: -1,
44
+ url,
45
+ },
46
+ };
47
+ page.state = PAGE_LOADING_STATE.CREATED;
56
48
 
57
- getStatsForDomain(domain) {
58
- return (this.requestStats[domain] ||= {});
59
- }
49
+ page.activeTime = 0;
50
+ page.activeFrom = active ? Date.now() : 0;
51
+
52
+ page.requestStats = {};
53
+ page.annotations = {};
54
+ page.counter = 0;
55
+ page.previous = null;
56
+ return page;
60
57
  }
61
58
 
62
59
  export default class PageStore {
@@ -88,7 +85,7 @@ export default class PageStore {
88
85
 
89
86
  unload() {
90
87
  this.#pages.forEach((serializedPage) => {
91
- const page = new Page(serializedPage);
88
+ const page = createPageFromTab(serializedPage);
92
89
  this.#stagePage(page);
93
90
  });
94
91
  this.#pages.clear();
@@ -115,7 +112,7 @@ export default class PageStore {
115
112
  }
116
113
 
117
114
  #stagePage(page) {
118
- page.setActive(false);
115
+ makePageActive(page, false);
119
116
  page.destroyed = Date.now();
120
117
  // unset previous (to prevent history chain memory leak)
121
118
  page.previous = undefined;
@@ -127,18 +124,21 @@ export default class PageStore {
127
124
  * Create a new `tabContext` for the new tab
128
125
  */
129
126
  #onTabCreated = (tab) => {
130
- this.#pages.set(tab.id, new Page(tab));
127
+ this.#pages.set(tab.id, createPageFromTab(tab));
131
128
  };
132
129
 
133
130
  /**
134
131
  * Update an existing tab or create it if we do not have a context yet.
135
132
  */
136
133
  #onTabUpdated = (tabId, info, tab) => {
137
- const page = new Page(this.#pages.get(tabId) || tab);
134
+ let page = this.#pages.get(tabId);
135
+ if (!page) {
136
+ page = createPageFromTab(tab);
137
+ }
138
138
 
139
139
  // Update `isPrivate` and `url` if available
140
140
  page.isPrivate = tab.incognito;
141
- page.setActive(tab.active);
141
+ makePageActive(page, tab.active);
142
142
  if (info.url !== undefined) {
143
143
  page.url = info.url;
144
144
  }
@@ -150,11 +150,10 @@ export default class PageStore {
150
150
  * Remove tab context for `tabId`.
151
151
  */
152
152
  #onTabRemoved = (tabId) => {
153
- const serializedPage = this.#pages.get(tabId);
154
- if (!serializedPage) {
153
+ const page = this.#pages.get(tabId);
154
+ if (!page) {
155
155
  return;
156
156
  }
157
- const page = new Page(serializedPage);
158
157
  if (page.state === PAGE_LOADING_STATE.COMPLETE) {
159
158
  this.#stagePage(page);
160
159
  }
@@ -166,21 +165,19 @@ export default class PageStore {
166
165
  // if previousTabId is not set (e.g. on chrome), set all tabs to inactive
167
166
  // otherwise, we only have to mark the previous tab as inactive
168
167
  if (!previousTabId) {
169
- for (const serializedPage of this.#pages.values()) {
170
- const page = new Page(serializedPage);
171
- page.setActive(false);
168
+ for (const page of this.#pages.values()) {
169
+ makePageActive(page, false);
172
170
  this.#pages.set(page.id, page);
173
171
  }
174
172
  } else if (this.#pages.has(previousTabId)) {
175
173
  const previousPage = this.#pages.get(previousTabId);
176
- const page = new Page(previousPage);
177
- page.setActive(false);
178
- this.#pages.set(page.id, page);
174
+ makePageActive(previousPage, false);
175
+ this.#pages.set(previousPage.id, previousPage);
179
176
  }
180
177
 
181
178
  if (this.#pages.has(tabId)) {
182
- const page = new Page(this.#pages.get(tabId));
183
- page.setActive(true);
179
+ const page = this.#pages.get(tabId);
180
+ makePageActive(page, true);
184
181
  this.#pages.set(page.id, page);
185
182
  }
186
183
  };
@@ -188,12 +185,11 @@ export default class PageStore {
188
185
  #onWindowFocusChanged = async (focusedWindowId) => {
189
186
  const activeTabs = await chrome.tabs.query({ active: true });
190
187
  for (const { id, windowId } of activeTabs) {
191
- const serializedPage = this.#pages.get(id);
192
- if (!serializedPage) {
188
+ const page = this.#pages.get(id);
189
+ if (!page) {
193
190
  continue;
194
191
  }
195
- const page = new Page(serializedPage);
196
- page.setActive(windowId === focusedWindowId);
192
+ makePageActive(page, windowId === focusedWindowId);
197
193
  this.#pages.set(id, page);
198
194
  }
199
195
  };
@@ -205,9 +201,7 @@ export default class PageStore {
205
201
  return;
206
202
  }
207
203
 
208
- const page = this.#pages.has(tabId)
209
- ? new Page(this.#pages.get(tabId))
210
- : null;
204
+ const page = this.#pages.get(tabId);
211
205
 
212
206
  if (page) {
213
207
  // ignore duplicated #onBeforeNavigate https://bugzilla.mozilla.org/show_bug.cgi?id=1732564
@@ -228,7 +222,7 @@ export default class PageStore {
228
222
  // create a new page for the navigation
229
223
  this.#pages.delete(tabId);
230
224
 
231
- const nextPage = new Page({
225
+ const nextPage = createPageFromTab({
232
226
  id: tabId,
233
227
  active: false,
234
228
  url,
@@ -242,14 +236,12 @@ export default class PageStore {
242
236
 
243
237
  #onNavigationCommitted = (details) => {
244
238
  const { frameId, tabId } = details;
245
- const serializedPage = this.#pages.get(tabId);
239
+ const page = this.#pages.get(tabId);
246
240
 
247
- if (!serializedPage) {
241
+ if (!page) {
248
242
  return;
249
243
  }
250
244
 
251
- const page = new Page(serializedPage);
252
-
253
245
  if (frameId === 0) {
254
246
  page.state = PAGE_LOADING_STATE.COMMITTED;
255
247
  this.#pages.set(tabId, page);
@@ -261,11 +253,10 @@ export default class PageStore {
261
253
 
262
254
  #onNavigationCompleted = (details) => {
263
255
  const { frameId, tabId } = details;
264
- const serializedPage = this.#pages.get(tabId);
265
- if (!serializedPage) {
256
+ const page = this.#pages.get(tabId);
257
+ if (!page) {
266
258
  return;
267
259
  }
268
- const page = new Page(serializedPage);
269
260
  if (frameId === 0) {
270
261
  page.state = PAGE_LOADING_STATE.COMPLETE;
271
262
  }
@@ -280,9 +271,9 @@ export default class PageStore {
280
271
  }
281
272
 
282
273
  // Update last request id from the tab
283
- const page = new Page(
284
- this.#pages.get(tabId) || { url, incognito: false, id: tabId },
285
- );
274
+ const page =
275
+ this.#pages.get(tabId) ||
276
+ createPageFromTab({ url, incognito: false, id: tabId });
286
277
 
287
278
  if (event === 'onBeforeRequest') {
288
279
  page.frames = {};
@@ -300,11 +291,10 @@ export default class PageStore {
300
291
 
301
292
  onSubFrame = (details) => {
302
293
  const { tabId, frameId, parentFrameId, url } = details;
303
- const serializedPage = this.#pages.get(tabId);
304
- if (!serializedPage) {
294
+ const page = this.#pages.get(tabId);
295
+ if (!page) {
305
296
  return;
306
297
  }
307
- const page = new Page(serializedPage);
308
298
  // Keep track of frameUrl as well as parent frame
309
299
  page.frames[frameId] = {
310
300
  parentFrameId,
@@ -315,11 +305,11 @@ export default class PageStore {
315
305
 
316
306
  getPageForRequest(context) {
317
307
  const { tabId, frameId, originUrl, type, initiator } = context;
318
- const serializedPage = this.#pages.get(tabId);
319
- if (!serializedPage) {
308
+ const page = this.#pages.get(tabId);
309
+ if (!page) {
320
310
  return null;
321
311
  }
322
- const page = new Page(serializedPage);
312
+
323
313
  // check if the current page has the given frame id, otherwise check if it belongs to the
324
314
  // previous page
325
315
  if (!page.frames[frameId]) {
@@ -12,7 +12,6 @@
12
12
  import { differenceInDays, parseISO, getUnixTime, sub } from 'date-fns';
13
13
 
14
14
  import PackedBloomFilter from './utils/bloom-filter-packed.js';
15
- import pacemaker from '../utils/pacemaker.js';
16
15
  import logger from '../logger.js';
17
16
 
18
17
  const STORAGE_CONFIG_KEY = 'qs_config';
@@ -172,7 +171,6 @@ export default class QSWhitelist2 {
172
171
  }
173
172
 
174
173
  async destroy() {
175
- pacemaker.clearTimeout(this._updateChecker);
176
174
  await this._persistBloomFilter();
177
175
  }
178
176
 
@@ -10,7 +10,6 @@
10
10
  */
11
11
 
12
12
  import { truncatedHash } from '../../md5.js';
13
- import pacemaker from '../../utils/pacemaker.js';
14
13
  import { parse } from '../../utils/url.js';
15
14
  import { sameGeneralDomain, getGeneralDomain } from '../utils/tlds.js';
16
15
  import logger from '../../logger.js';
@@ -46,13 +45,15 @@ export default class CookieContext {
46
45
  await this.visitCache.isReady;
47
46
  await this.trustedThirdParties.isReady;
48
47
  this.cleanCookieCache();
49
- this._pmclean = pacemaker.register(this.cleanCookieCache.bind(this), {
50
- timeout: CLEAN_COOKIE_CACHE_TIMEOUT,
51
- });
48
+ this._pmclean = setInterval(
49
+ this.cleanCookieCache.bind(this),
50
+ CLEAN_COOKIE_CACHE_TIMEOUT,
51
+ );
52
52
  }
53
53
 
54
54
  unload() {
55
- this._pmclean = pacemaker.clearTimeout(this._pmclean);
55
+ clearInterval(this._pmclean);
56
+ this._pmclean = null;
56
57
  }
57
58
 
58
59
  cleanCookieCache() {
@@ -10,7 +10,6 @@
10
10
  */
11
11
 
12
12
  import { parse } from '../../utils/url.js';
13
- import Subject from '../utils/subject.js';
14
13
  import ChromeStorageMap from '../utils/chrome-storage-map.js';
15
14
 
16
15
  const DEFAULT_OPTIONS = {
@@ -30,40 +29,20 @@ export default class OAuthDetector {
30
29
  storageKey: 'wtm-request-reporting:oauth-detector:site-activity',
31
30
  ttlInMs: this.VISIT_TIMEOUT,
32
31
  });
33
- this.subjectMainFrames = new Subject();
34
- this.tabClicks = new Subject();
35
32
  }
36
33
 
37
- recordClick(ev, contextHTML, href, sender) {
38
- this.tabClicks.pub(sender.tab);
34
+ recordClick(sender) {
35
+ this.clickActivity.set(sender.tab.id, sender.tab.url);
39
36
  }
40
37
 
41
38
  async init() {
42
39
  await this.clickActivity.isReady;
43
40
  await this.siteActivitiy.isReady;
44
- this.tabActivitySubscription = this.tabClicks.subscribe((event) => {
45
- this.clickActivity.set(event.id, event.url);
46
- });
47
- this.pageOpenedSubscription = this.subjectMainFrames.subscribe((event) => {
48
- this.siteActivitiy.set(event.hostname, event.tabId);
49
- });
50
- }
51
-
52
- unload() {
53
- if (this.tabActivitySubscription) {
54
- this.tabActivitySubscription.unsubscribe();
55
- }
56
- if (this.pageOpenedSubscription) {
57
- this.pageOpenedSubscription.unsubscribe();
58
- }
59
41
  }
60
42
 
61
43
  checkMainFrames(state) {
62
44
  if (state.isMainFrame) {
63
- this.subjectMainFrames.pub({
64
- tabId: state.tabId,
65
- hostname: state.urlParts.hostname,
66
- });
45
+ this.siteActivitiy.set(state.urlParts.hostname, state.tabId);
67
46
  }
68
47
  }
69
48
 
@@ -11,7 +11,7 @@
11
11
 
12
12
  /* eslint no-param-reassign: 'off' */
13
13
 
14
- import { truncateDomain } from '../utils.js';
14
+ import { truncateDomain } from '../utils/utils.js';
15
15
 
16
16
  // maps string (web-ext) to int (FF cpt). Anti-tracking still uses these legacy types.
17
17
  const TYPE_LOOKUP = {
@@ -45,9 +45,8 @@ export default class PageLogger {
45
45
  }
46
46
 
47
47
  _attachCounters(state) {
48
- const stats = state.page.getStatsForDomain(
49
- truncateDomain(state.urlParts.domainInfo, 2),
50
- );
48
+ const domain = truncateDomain(state.urlParts.domainInfo, 2);
49
+ const stats = (state.page.requestStats[domain] ||= {});
51
50
  state.reqLog = stats;
52
51
  const incrementStat = (statName, c) => {
53
52
  stats[statName] = (stats[statName] || 0) + (c || 1);
@@ -9,7 +9,7 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
- import * as datetime from '../../time.js';
12
+ import * as datetime from '../../utils/time.js';
13
13
  import logger from '../../../logger.js';
14
14
  import ChromeStorageMap from '../../utils/chrome-storage-map.js';
15
15
 
@@ -11,9 +11,8 @@
11
11
 
12
12
  /* eslint no-param-reassign: 'off' */
13
13
 
14
- import * as datetime from '../time.js';
14
+ import * as datetime from '../utils/time.js';
15
15
  import md5, { truncatedHash } from '../../md5.js';
16
- import pacemaker from '../../utils/pacemaker.js';
17
16
  import ChromeStorageMap from '../utils/chrome-storage-map.js';
18
17
  import logger from '../../logger.js';
19
18
 
@@ -40,7 +39,7 @@ export default class TokenExaminer {
40
39
  }
41
40
 
42
41
  unload() {
43
- pacemaker.clearTimeout(this._syncTimer);
42
+ clearTimeout(this._syncTimer);
44
43
  this._syncTimer = null;
45
44
  }
46
45
 
@@ -153,7 +152,7 @@ export default class TokenExaminer {
153
152
  this._syncTimer = null;
154
153
  }
155
154
  };
156
- this._syncTimer = pacemaker.setTimeout(syncDb, SYNC_DB_INTERVAL);
155
+ this._syncTimer = setTimeout(syncDb, SYNC_DB_INTERVAL);
157
156
  }
158
157
 
159
158
  async _syncDb() {
@@ -9,8 +9,6 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
- import logger from '../../../logger.js';
13
- import Subject from '../../utils/subject.js';
14
12
  import ChromeStorageMap from '../../utils/chrome-storage-map.js';
15
13
 
16
14
  const CACHE_TTL = 2 * 24 * 60 * 60 * 1000; // 2 days
@@ -19,16 +17,19 @@ const CACHE_TTL = 2 * 24 * 60 * 60 * 1000; // 2 days
19
17
  * Abstract part of token/key processing logic.
20
18
  */
21
19
  export default class CachedEntryPipeline {
22
- constructor({ name, db, trustedClock, primaryKey, options }) {
23
- this.name = name;
24
- this.db = db;
25
- this.trustedClock = trustedClock;
20
+ constructor(params) {
21
+ this.name = params.name;
22
+ this.db = params.db;
23
+ this.trustedClock = params.trustedClock;
26
24
  this.cache = new ChromeStorageMap({
27
- storageKey: `wtm-request-reporting:token-telemetry:${name}`,
25
+ storageKey: `wtm-request-reporting:token-telemetry:${this.name}`,
28
26
  ttlInMs: CACHE_TTL,
29
27
  });
30
- this.primaryKey = primaryKey;
31
- this.options = options;
28
+ this.primaryKey = params.primaryKey;
29
+ this.options = params.options;
30
+ this.sendMessage = params.sendMessage;
31
+ this.batchInterval = params.batchInterval;
32
+ this.batchLimit = params.batchLimit;
32
33
  }
33
34
 
34
35
  get(key) {
@@ -66,84 +67,63 @@ export default class CachedEntryPipeline {
66
67
  * by #serialiseEntry
67
68
  * @param keys
68
69
  */
69
- saveBatchToDb(keys) {
70
+ async saveBatchToDb(keys) {
70
71
  const rows = keys.map((key) => {
71
72
  const entry = this.getFromCache(key);
72
73
  entry.dirty = false;
73
74
  return this.serialiseEntry(key, entry);
74
75
  });
75
- return this.db.bulkPut(rows);
76
+ await this.db.bulkPut(rows);
76
77
  }
77
78
 
78
- /**
79
- * Create an Rx pipeline to process a stream of tokens or keys at regular intervals
80
- * and pushes generated messages to the outputSubject.
81
- * @param inputObservable Observable input to the pipeline
82
- * @param outputSubject Subject for outputed messages
83
- * @param batchInterval how often to run batches
84
- * @param batchLimit maximum messages per batch
85
- */
86
- async init(
87
- inputObservable,
88
- sendMessage,
89
- batchInterval,
90
- batchLimit,
91
- overflowSubject,
92
- ) {
79
+ async init() {
93
80
  await this.cache.isReady;
94
- const pipeline = new Subject();
95
- this.input = inputObservable;
96
-
97
- let batch = [];
81
+ this.batch = [];
98
82
  setInterval(() => {
99
- pipeline.pub(batch);
100
- batch = [];
101
- }, batchInterval);
102
-
103
- inputObservable.subscribe((token) => {
104
- batch.push(token);
105
- });
106
-
107
- pipeline.subscribe(async (batch) => {
108
- try {
109
- // merge existing entries from DB
110
- await this.loadBatchIntoCache(batch);
111
- // extract message and clear
112
- const today = this.trustedClock.getTimeAsYYYYMMDD();
113
- const toBeSent = batch
114
- .map((token) => [token, this.getFromCache(token)])
115
- .filter(([, { lastSent }]) => lastSent !== today);
116
-
117
- // generate the set of messages to be sent from the candiate list
118
- const { messages, overflow } = this.createMessagePayloads(
119
- toBeSent,
120
- batchLimit,
121
- );
122
- // get the keys of the entries not being sent this time
123
- const overflowKeys = new Set(overflow.map((tup) => tup[0]));
124
-
125
- // update lastSent for sent messages
126
- toBeSent
127
- .filter((tup) => !overflowKeys.has(tup[0]))
128
- .forEach(([, _entry]) => {
129
- const entry = _entry;
130
- entry.lastSent = this.trustedClock.getTimeAsYYYYMMDD();
131
- });
132
-
133
- await this.saveBatchToDb(batch);
134
- // clear the distinct map
135
- messages.forEach((msg) => {
136
- sendMessage(msg);
137
- });
138
- // push overflowed entries back into the queue
139
- overflowKeys.forEach((k) => overflowSubject.pub(k));
140
- } catch (e) {
141
- logger.error('Failed to initialize stream', e);
83
+ if (this.batch.length > 0) {
84
+ this.#processBatch([...this.batch]);
85
+ this.batch = [];
142
86
  }
143
- });
87
+ }, this.batchInterval);
88
+ }
89
+
90
+ processEntry(entry) {
91
+ this.batch.push(entry);
144
92
  }
145
93
 
146
- unload() {}
94
+ async #processBatch(batch) {
95
+ // merge existing entries from DB
96
+ await this.loadBatchIntoCache(batch);
97
+ // extract message and clear
98
+ const today = this.trustedClock.getTimeAsYYYYMMDD();
99
+ const toBeSent = batch
100
+ .map((token) => [token, this.getFromCache(token)])
101
+ .filter(([, { lastSent }]) => lastSent !== today);
102
+
103
+ // generate the set of messages to be sent from the candiate list
104
+ const { messages, overflow } = this.createMessagePayloads(
105
+ toBeSent,
106
+ this.batchLimit,
107
+ );
108
+ // get the keys of the entries not being sent this time
109
+ const overflowKeys = new Set(overflow.map((tup) => tup[0]));
110
+
111
+ // update lastSent for sent messages
112
+ toBeSent
113
+ .filter((tup) => !overflowKeys.has(tup[0]))
114
+ .forEach(([, _entry]) => {
115
+ const entry = _entry;
116
+ entry.lastSent = this.trustedClock.getTimeAsYYYYMMDD();
117
+ });
118
+
119
+ await this.saveBatchToDb(batch);
120
+ // clear the distinct map
121
+ for (const message of messages) {
122
+ this.sendMessage(message);
123
+ }
124
+ // push overflowed entries back into the queue
125
+ overflowKeys.forEach((k) => this.processEntry(k));
126
+ }
147
127
 
148
128
  /**
149
129
  * Periodic task to take unsent values from the database and push them to be sent,