-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
424 lines (370 loc) · 12.5 KB
/
index.ts
File metadata and controls
424 lines (370 loc) · 12.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
import './env';
import * as crypto from 'crypto';
import * as mongodb from 'mongodb';
import { DatabaseController } from '../../../lib/db/controller';
import * as utils from '../../../lib/utils';
import { Worker } from '../../../lib/worker';
import * as WorkerNames from '../../../lib/workerNames';
import * as pkg from '../package.json';
import { GroupWorkerTask } from '../types/group-worker-task';
import { EventAddons, EventDataAccepted, GroupedEventDBScheme, RepetitionDBScheme } from 'hawk.types';
import { DatabaseReadWriteError, ValidationError } from '../../../lib/workerErrors';
import { decodeUnsafeFields, encodeUnsafeFields } from '../../../lib/utils/unsafeFields';
import HawkCatcher from '@hawk.so/nodejs';
import { MS_IN_SEC } from '../../../lib/utils/consts';
import DataFilter from './data-filter';
import RedisHelper from './redisHelper';
import levenshtein from 'js-levenshtein';
/**
* Error code of MongoDB key duplication error
*/
const DB_DUPLICATE_KEY_ERROR = '11000';
/**
* Worker for handling Javascript events
*/
export default class GrouperWorker extends Worker {
/**
* Worker type
*/
public readonly type: string = pkg.workerType;
/**
* Database Controller
*/
private db: DatabaseController = new DatabaseController(process.env.MONGO_EVENTS_DATABASE_URI);
/**
* This class will filter sensitive information
*/
private dataFilter = new DataFilter();
/**
* Redis helper instance for modifying data through redis
*/
private redis = new RedisHelper();
/**
* Start consuming messages
*/
public async start(): Promise<void> {
await this.db.connect();
this.prepareCache();
await super.start();
}
/**
* Finish everything
*/
public async finish(): Promise<void> {
await super.finish();
await this.db.close();
}
/**
* Task handling function
*
* @param task - event to handle
*/
public async handle(task: GroupWorkerTask): Promise<void> {
let uniqueEventHash = await this.getUniqueEventHash(task);
/**
* Find event by group hash.
*/
let existedEvent = await this.getEvent(task.projectId, {
groupHash: uniqueEventHash,
});
/**
* If we couldn't group by group hash (title), try grouping by Levenshtein distance with last N events
*/
if (!existedEvent) {
const similarEvent = await this.findSimilarEvent(task.projectId, task.event);
if (similarEvent) {
/**
* Override group hash with found event's group hash
*/
uniqueEventHash = similarEvent.groupHash;
existedEvent = similarEvent;
}
}
/**
* Event happened for the first time
*/
const isFirstOccurrence = existedEvent === null;
let repetitionId = null;
/**
* Filter sensitive information
*/
this.dataFilter.processEvent(task.event);
if (isFirstOccurrence) {
try {
/**
* Insert new event
*/
await this.saveEvent(task.projectId, {
groupHash: uniqueEventHash,
totalCount: 1,
catcherType: task.catcherType,
payload: task.event,
usersAffected: 1,
} as GroupedEventDBScheme);
} catch (e) {
/**
* If we caught Database duplication error, then another worker thread has already saved it to the database
* and we need to process this event as repetition
*/
if (e.code?.toString() === DB_DUPLICATE_KEY_ERROR) {
HawkCatcher.send(new Error('[Grouper] MongoError: E11000 duplicate key error collection'));
await this.handle(task);
} else {
throw e;
}
}
} else {
const incrementAffectedUsers = await this.shouldIncrementAffectedUsers(task, existedEvent);
/**
* Increment existed task's counter
*/
await this.incrementEventCounterAndAffectedUsers(task.projectId, {
groupHash: uniqueEventHash,
}, incrementAffectedUsers);
/**
* Decode existed event to calculate diffs correctly
*/
decodeUnsafeFields(existedEvent);
/**
* Save event's repetitions
*
* Leave timestamp in diff for database queries
*/
const diff = utils.deepDiff(existedEvent.payload, task.event, [ 'timestamp' ]);
const newRepetition = {
groupHash: uniqueEventHash,
payload: diff,
} as RepetitionDBScheme;
repetitionId = await this.saveRepetition(task.projectId, newRepetition);
}
/**
* Store events counter by days
*/
await this.saveDailyEvents(task.projectId, uniqueEventHash, task.event.timestamp, repetitionId);
/**
* Add task for NotifierWorker
*/
if (process.env.IS_NOTIFIER_WORKER_ENABLED) {
await this.addTask(WorkerNames.NOTIFIER, {
projectId: task.projectId,
event: {
title: task.event.title,
groupHash: uniqueEventHash,
isNew: isFirstOccurrence,
},
});
}
}
/**
* Get unique hash based on event type and title
*
* @param task - worker task to create hash
*/
private getUniqueEventHash(task: GroupWorkerTask): Promise<string> {
return this.cache.get(`groupHash:${task.projectId}:${task.catcherType}:${task.event.title}`, () => {
return crypto.createHmac('sha256', process.env.EVENT_SECRET)
.update(task.catcherType + task.event.title)
.digest('hex');
});
}
/**
* Tries to find events with a small Levenshtein distance of a title
*
* @param projectId - where to find
* @param event - event to compare
*/
private async findSimilarEvent(projectId: string, event: EventDataAccepted<EventAddons>): Promise<GroupedEventDBScheme | undefined> {
const eventsCountToCompare = 60;
const diffTreshold = 0.35;
const lastUniqueEvents = await this.findLastEvents(projectId, eventsCountToCompare);
return lastUniqueEvents.filter(prevEvent => {
const distance = levenshtein(event.title, prevEvent.payload.title);
const threshold = event.title.length * diffTreshold;
return distance < threshold;
}).pop();
}
/**
* Returns last N unique events by a project id
*
* @param projectId - where to find
* @param count - how many events to return
*/
private findLastEvents(projectId: string, count): Promise<GroupedEventDBScheme[]> {
const msInOneMinute = 60000;
return this.cache.get(`last:${count}:eventsOf:${projectId}`, async () => {
return this.db.getConnection()
.collection(`events:${projectId}`)
.find()
.sort({
_id: 1,
})
.limit(count)
.toArray();
}, msInOneMinute);
}
/**
* Decides whether to increase the number of affected users.
*
* @param task - worker task to process
* @param existedEvent - original event to get its user
*/
private async shouldIncrementAffectedUsers(task: GroupWorkerTask, existedEvent: GroupedEventDBScheme): Promise<boolean> {
const eventUser = task.event.user;
if (!eventUser) {
return false;
}
const isUserFromOriginalEvent = existedEvent.payload.user?.id === eventUser.id;
if (isUserFromOriginalEvent) {
return false;
} else {
const repetitionCacheKey = `repetitions:${task.projectId}:${existedEvent.groupHash}:${eventUser.id}`;
const repetition = await this.cache.get(repetitionCacheKey, async () => {
return this.db.getConnection().collection(`repetitions:${task.projectId}`)
.findOne({
groupHash: existedEvent.groupHash,
'payload.user.id': eventUser.id,
});
});
if (repetition) {
return false;
}
const isLocked = await this.redis.checkOrSetEventLock(existedEvent.groupHash, eventUser.id);
return !isLocked;
}
}
/**
* Returns finds event by query from project with passed ID
*
* @param projectId - project's identifier
* @param query - mongo query string
*/
private async getEvent(projectId: string, query: Record<string, unknown>): Promise<GroupedEventDBScheme> {
if (!mongodb.ObjectID.isValid(projectId)) {
throw new ValidationError('Controller.saveEvent: Project ID is invalid or missed');
}
const eventCacheKey = `${projectId}:${JSON.stringify(query)}`;
return this.cache.get(eventCacheKey, async () => {
return this.db.getConnection()
.collection(`events:${projectId}`)
.findOne(query)
.catch((err) => {
throw new DatabaseReadWriteError(err);
});
});
}
/**
* Save event to database
*
* @param projectId - project id
* @param groupedEventData - event data
* @throws {ValidationError} if `projectID` is not provided or invalid
* @throws {ValidationError} if `eventData` is not a valid object
*/
private async saveEvent(projectId: string, groupedEventData: GroupedEventDBScheme): Promise<mongodb.ObjectID> {
if (!projectId || !mongodb.ObjectID.isValid(projectId)) {
throw new ValidationError('Controller.saveEvent: Project ID is invalid or missed');
}
const collection = this.db.getConnection().collection(`events:${projectId}`);
encodeUnsafeFields(groupedEventData);
return (await collection
.insertOne(groupedEventData)).insertedId as mongodb.ObjectID;
}
/**
* Inserts unique event repetition to the database
*
* @param projectId - project's identifier
* @param {RepetitionDBScheme} repetition - object that contains only difference with first event
*/
private async saveRepetition(projectId: string, repetition: RepetitionDBScheme): Promise<mongodb.ObjectID> {
if (!projectId || !mongodb.ObjectID.isValid(projectId)) {
throw new ValidationError('Controller.saveRepetition: Project ID is invalid or missing');
}
try {
const collection = this.db.getConnection().collection(`repetitions:${projectId}`);
encodeUnsafeFields(repetition);
return (await collection.insertOne(repetition)).insertedId as mongodb.ObjectID;
} catch (err) {
throw new DatabaseReadWriteError(err);
}
}
/**
* If event in project exists this method increments counter
*
* @param projectId - project id to increment
* @param query - query to get event
* @param incrementAffected - if true, usersAffected counter will be incremented
*/
private async incrementEventCounterAndAffectedUsers(projectId, query, incrementAffected: boolean): Promise<number> {
if (!projectId || !mongodb.ObjectID.isValid(projectId)) {
throw new ValidationError('Controller.saveEvent: Project ID is invalid or missed');
}
try {
const updateQuery = incrementAffected
? {
$inc: {
totalCount: 1,
usersAffected: 1,
},
}
: {
$inc: {
totalCount: 1,
},
};
return (await this.db.getConnection()
.collection(`events:${projectId}`)
.updateOne(query, updateQuery)).modifiedCount;
} catch (err) {
throw new DatabaseReadWriteError(err);
}
}
/**
* Saves event at the special aggregation collection
*
* @param {string} projectId - project's identifier
* @param {string} eventHash - event hash
* @param {string} eventTimestamp - timestamp of the last event
* @param {string|null} repetitionId - event's last repetition id
* @returns {Promise<void>}
*/
private async saveDailyEvents(
projectId: string,
eventHash: string,
eventTimestamp: number,
repetitionId: string | null
): Promise<void> {
if (!projectId || !mongodb.ObjectID.isValid(projectId)) {
throw new ValidationError('GrouperWorker.saveDailyEvents: Project ID is invalid or missed');
}
try {
/**
* Get JavaScript date from event unixtime to convert daily aggregation collection format
*
* Problem was issued due to the numerous events that could be occurred in the past
* but the date always was current
*/
const eventDate = new Date(eventTimestamp * MS_IN_SEC);
eventDate.setUTCHours(0, 0, 0, 0); // 00:00 UTC
const midnight = eventDate.getTime() / MS_IN_SEC;
await this.db.getConnection()
.collection(`dailyEvents:${projectId}`)
.updateOne(
{
groupHash: eventHash,
groupingTimestamp: midnight,
},
{
$set: {
groupHash: eventHash,
groupingTimestamp: midnight,
lastRepetitionTime: eventTimestamp,
lastRepetitionId: repetitionId,
},
$inc: { count: 1 },
},
{ upsert: true });
} catch (err) {
throw new DatabaseReadWriteError(err);
}
}
}