@whotracksme/reporting 7.12.3 → 8.0.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.
Files changed (44) hide show
  1. package/.eslintignore +1 -0
  2. package/CHANGELOG.md +24 -0
  3. package/communication/test/helpers/in-memory-database.js +45 -0
  4. package/package.json +1 -1
  5. package/reporting/README.md +26 -0
  6. package/reporting/example/README.md +65 -0
  7. package/reporting/example/logs/.gitignore +2 -0
  8. package/reporting/example/run.mjs +288 -0
  9. package/reporting/karma.conf.cjs +3 -2
  10. package/reporting/package.json +8 -2
  11. package/reporting/rollup.common-config.cjs +7 -1
  12. package/reporting/scenarios/README.md +77 -0
  13. package/reporting/src/hash-detector-v2/index.js +164 -0
  14. package/reporting/src/hash-detector-v2/prob.js +599 -0
  15. package/reporting/src/hash-detector-v2.js +18 -0
  16. package/reporting/src/observable.js +43 -0
  17. package/reporting/src/pages.js +11 -12
  18. package/reporting/src/paused-domains-reporter.js +50 -0
  19. package/reporting/src/persisted-counters.js +158 -0
  20. package/reporting/src/popularity-estimator.js +625 -0
  21. package/reporting/src/popularity-vote-handler.js +219 -0
  22. package/reporting/src/popularity-vote-sanitizer.js +384 -0
  23. package/reporting/src/random.js +90 -1
  24. package/reporting/src/reporting.js +98 -13
  25. package/reporting/src/utils.js +41 -1
  26. package/reporting/test/README.md +42 -2
  27. package/reporting/test/activity-estimator.spec.js +3 -2
  28. package/reporting/test/alive-check.spec.js +2 -2
  29. package/reporting/test/country-provider.spec.js +2 -2
  30. package/reporting/test/helpers/scenarios.js +4 -1
  31. package/reporting/test/index.js +6 -0
  32. package/reporting/test/job-scheduler.spec.js +2 -2
  33. package/reporting/test/observable.spec.js +72 -0
  34. package/reporting/test/page-aggregator.spec.js +3 -0
  35. package/reporting/test/patterns-updater.spec.js +2 -2
  36. package/reporting/test/persisted-counters.spec.js +132 -0
  37. package/reporting/test/popularity-estimator.spec.js +710 -0
  38. package/reporting/test/popularity-vote-handler.spec.js +420 -0
  39. package/reporting/test/popularity-vote-sanitizer.spec.js +635 -0
  40. package/reporting/test/random.spec.js +157 -0
  41. package/reporting/test/reporting.spec.js +202 -180
  42. package/reporting/test/request/index.test.js +6 -2
  43. package/reporting/test/request.js +14 -0
  44. package/reporting/test/utils.spec.js +42 -0
@@ -20,6 +20,7 @@ import {
20
20
  } from './utils';
21
21
  import { DnsResolver } from './network';
22
22
  import ActivityEstimator from './activity-estimator';
23
+ import Observable from './observable';
23
24
  import { analyzePageStructure } from './page-structure';
24
25
  import EventListenerQueue from './event-listener-queue';
25
26
  import SelfCheck from './self-check';
@@ -343,7 +344,7 @@ export default class Pages {
343
344
  this.isActive = false;
344
345
  this.urlAnalyzer = requireParam(urlAnalyzer);
345
346
  this.newPageApprover = requireParam(newPageApprover);
346
- this.observers = [];
347
+ this._observable = new Observable();
347
348
 
348
349
  this.openTabs = new OpenTabs(this);
349
350
  this.activeTab = new ActiveTab(this);
@@ -387,7 +388,15 @@ export default class Pages {
387
388
  }
388
389
 
389
390
  addObserver(onPageEventCallback) {
390
- this.observers.push(onPageEventCallback);
391
+ this._observable.addObserver(onPageEventCallback);
392
+ }
393
+
394
+ removeObserver(onPageEventCallback) {
395
+ this._observable.removeObserver(onPageEventCallback);
396
+ }
397
+
398
+ notifyObservers(event) {
399
+ this._observable.notifyObservers(event);
391
400
  }
392
401
 
393
402
  async init() {
@@ -727,16 +736,6 @@ export default class Pages {
727
736
  eventListenerQueue.close();
728
737
  }
729
738
 
730
- notifyObservers(event) {
731
- this.observers.forEach((observer) => {
732
- try {
733
- observer(event);
734
- } catch (e) {
735
- logger.error('Unexpected error in observer', e);
736
- }
737
- });
738
- }
739
-
740
739
  describe(now = Date.now()) {
741
740
  const openTabs = {};
742
741
  for (const [tabId, pageInfo] of this.openTabs) {
@@ -0,0 +1,50 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://whotracks.me/
4
+ *
5
+ * Copyright 2017-present Ghostery GmbH. All rights reserved.
6
+ *
7
+ * This Source Code Form is subject to the terms of the Mozilla Public
8
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
9
+ * file, You can obtain one at http://mozilla.org/MPL/2.0
10
+ */
11
+
12
+ import logger from './logger';
13
+ import { requireParam } from './utils';
14
+
15
+ export default class PausedDomainsReporter {
16
+ constructor({ filterModeProvider }) {
17
+ this.active = false;
18
+ this.filterModeProvider = requireParam(filterModeProvider);
19
+ }
20
+
21
+ async init() {
22
+ this.active = true;
23
+ }
24
+
25
+ unload() {
26
+ this.active = false;
27
+ }
28
+
29
+ onPauseEvent({ hostname, paused }) {
30
+ if (!this.active) {
31
+ return;
32
+ }
33
+
34
+ logger.info(hostname, 'is now', paused ? 'paused' : 'unpaused');
35
+ const filterMode = this.filterModeProvider();
36
+ const event = { filterMode, hostname, paused, ts: Date.now() };
37
+
38
+ this._processEvent(event).catch((e) => {
39
+ logger.error('Failed to process event', event, e);
40
+ });
41
+ }
42
+
43
+ async _processEvent(event) {
44
+ // TODO:
45
+ logger.warn(
46
+ '[STUB] handing of pause/unpause is not yet implemented',
47
+ event,
48
+ );
49
+ }
50
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://whotracks.me/
4
+ *
5
+ * Copyright 2017-present Ghostery GmbH. All rights reserved.
6
+ *
7
+ * This Source Code Form is subject to the terms of the Mozilla Public
8
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
9
+ * file, You can obtain one at http://mozilla.org/MPL/2.0
10
+ */
11
+
12
+ import logger from './logger';
13
+ import { requireString, requireObject } from './utils';
14
+ import { randomSafeIntBetween, shuffleInPlace } from './random';
15
+
16
+ // Example: ['foo', 'foo', 'bar'] ==> [['foo', 2], ['bar', 1]]
17
+ function groupConsecutive(arr) {
18
+ if (arr.length === 0) {
19
+ return [];
20
+ }
21
+ const result = [];
22
+ let current = arr[0];
23
+ let count = 1;
24
+
25
+ for (let i = 1; i < arr.length; i += 1) {
26
+ if (arr[i] === current) {
27
+ count += 1;
28
+ } else {
29
+ result.push([current, count]);
30
+ current = arr[i];
31
+ count = 1;
32
+ }
33
+ }
34
+ result.push([current, count]);
35
+
36
+ return result;
37
+ }
38
+
39
+ export default class PersistedCounters {
40
+ constructor({ name, db }) {
41
+ this.name = requireString(name);
42
+ this.db = requireObject(db);
43
+
44
+ this._pendingCounters = new Map();
45
+ this._pendingFlush = null;
46
+ }
47
+
48
+ count(key) {
49
+ this._pendingCounters.set(key, (this._pendingCounters.get(key) || 0) + 1);
50
+ this._markDirty();
51
+ }
52
+
53
+ async clear() {
54
+ this._pendingCounters.clear();
55
+ await this.db.clear();
56
+ }
57
+
58
+ async flush() {
59
+ this._pendingFlush = null;
60
+ if (this._pendingCounters.size === 0) {
61
+ return;
62
+ }
63
+
64
+ await this.db.transaction({ readonly: false }, async (tx) => {
65
+ const entries = [...this._pendingCounters];
66
+ this._pendingCounters.clear();
67
+
68
+ await Promise.all(
69
+ entries.map(async ([key, inc]) => {
70
+ const oldValue = (await tx.get(key)) || 0;
71
+ await tx.set(key, oldValue + inc);
72
+ }),
73
+ );
74
+ });
75
+ logger.debug('Flushed counters:', this.name);
76
+ }
77
+
78
+ /**
79
+ * Draws random samples.
80
+ *
81
+ * Options:
82
+ * - "group": Aggregates identical samples together
83
+ * Example: ['foo', 'foo', 'bar'] ==> [['foo', 2], ['bar', 1]]
84
+ */
85
+ async sample(numSamples = 1, { group = false } = {}) {
86
+ // Flush pending counters, so the database becomes the only source of truth.
87
+ // If new counts are being added afterwards, we will not see them, but this
88
+ // is expected; we are then operating on a safe snapshot.
89
+ await this.flush();
90
+
91
+ let samples = [];
92
+ if (numSamples > 0) {
93
+ await this.db.transaction({ readonly: true }, async (tx) => {
94
+ // Initial pass to learn how many counts we had in total
95
+ let cursor = await tx.scan();
96
+ let totalSum = 0;
97
+ while (cursor) {
98
+ totalSum += cursor.value;
99
+ cursor = await cursor.next();
100
+ }
101
+ if (totalSum > 0) {
102
+ // Draw the position of the random samples
103
+ const picks = [];
104
+ for (let i = 0; i < numSamples; i += 1) {
105
+ picks.push(randomSafeIntBetween(0, totalSum - 1));
106
+ }
107
+
108
+ // Second pass to identify the chosen samples
109
+ cursor = await tx.scan();
110
+ let currentSum = 0;
111
+ while (cursor && samples.length < numSamples) {
112
+ currentSum += cursor.value;
113
+ for (let i = 0; i < picks.length; i += 1) {
114
+ if (currentSum > picks[i]) {
115
+ samples.push(cursor.key);
116
+ picks[i] = Number.MAX_VALUE;
117
+ }
118
+ }
119
+ cursor = await cursor.next();
120
+ }
121
+ }
122
+ });
123
+
124
+ if (group) {
125
+ // Group identical values together (['foo', 'foo'] => [['foo', 2]]).
126
+ // By design, identical values are always next to each other.
127
+ samples = groupConsecutive(samples);
128
+ }
129
+ }
130
+
131
+ // Do a final shuffle to randomize the order; otherwise, the implicit
132
+ // order of the database may leak through.
133
+ return shuffleInPlace(samples);
134
+ }
135
+
136
+ /*
137
+ * Debug function: convert the counters to an ES6 map
138
+ *
139
+ * Do not use this function for production code! If you need to
140
+ * iterate over a database, there are more efficient ways.
141
+ */
142
+ async _dumpToMap() {
143
+ await this.flush();
144
+ return this.db._dumpToMap();
145
+ }
146
+
147
+ _markDirty() {
148
+ if (this._pendingFlush === null) {
149
+ this._pendingFlush = setTimeout(() => {
150
+ this.flush().catch(logger.error);
151
+ }, 200);
152
+ }
153
+ }
154
+
155
+ toString() {
156
+ return `PersistedCounters[${this.name}]`;
157
+ }
158
+ }