-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patheventsFactory.js
More file actions
575 lines (505 loc) · 14 KB
/
eventsFactory.js
File metadata and controls
575 lines (505 loc) · 14 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
573
574
575
import { getMidnightWithTimezoneOffset, getUTCMidnight } from '../utils/dates';
import { groupBy } from '../utils/grouper';
import safe from 'safe-regex';
const Factory = require('./modelFactory');
const mongo = require('../mongo');
const Event = require('../models/event');
const { ObjectID } = require('mongodb');
/**
* @typedef {Object} RecentEventSchema
* @property {Event} event - event model
* @property {Number} count - recent error occurred count
* @property {String} data - error occurred date (string)
*/
/**
* @typedef {Object} EventRepetitionSchema
* @property {String} _id — repetition's identifier
* @property {String} groupHash - event's hash. Generates according to the rule described in EventSchema
* @property {EventPayload} payload - repetition's payload
*/
/**
* @typedef {Object} EventsFilters
* @property {boolean} [starred] - if true, events with 'starred' mark should be included to the output
* @property {boolean} [resolved] - if true, events with 'resolved' should be included to the output
* @property {boolean} [ignored] - if true, events with 'ignored' mark should be included to the output
*/
/**
* EventsFactory
*
* Factory Class for Event's Model
*/
class EventsFactory extends Factory {
/**
* Event types with collections where they stored
* @return {{EVENTS: string, DAILY_EVENTS: string, REPETITIONS: string, RELEASES: string}}
* @constructor
*/
get TYPES() {
return {
EVENTS: 'events',
REPETITIONS: 'repetitions',
DAILY_EVENTS: 'dailyEvents',
RELEASES: 'releases',
};
}
/**
* Creates Event instance
* @param {ObjectId} projectId - project ID
*/
constructor(projectId) {
super();
if (!projectId) {
throw new Error('Can not construct Event model, because projectId is not provided');
}
this.projectId = projectId;
}
/**
* Returns pointer to the collection
*
* @param {String} type - each events in order to optimization holds data in different collections.
* This argument defines which collection need to be used.
*
* @returns {String}
*/
getCollection(type) {
return mongo.databases.events.collection(
type + ':' + this.projectId
);
}
/**
* Is collection of events exists
*
* @param {String} type - type of collection to check
*
* @return {Promise<boolean>}
*/
isCollectionExists(type) {
return mongo.databases.events.listCollections({ name: type + ':' + this.projectId }).hasNext();
}
/**
* Finds events by passed query
*
* @param {object} [query={}] - query
* @param {Number} [limit=10] - query limit
* @param {Number} [skip=0] - query skip
* @returns {Event[]} - events matching query
*/
async find(query = {}, limit = 10, skip = 0) {
limit = this.validateLimit(limit);
skip = this.validateSkip(skip);
const cursor = this.getCollection(this.TYPES.EVENTS)
.find(query)
.sort([ ['_id', -1] ])
.limit(limit)
.skip(skip);
const result = await cursor.toArray();
return result.map(eventSchema => {
return new Event({
...eventSchema,
projectId: this.projectId,
});
});
}
/**
* Find event by id
*
* @param {string|ObjectID} id - event's id
* @returns {Event|null}
*/
async findById(id) {
const searchResult = await this.getCollection(this.TYPES.EVENTS)
.findOne({
_id: new ObjectID(id),
});
return searchResult ? new Event(searchResult) : null;
}
/**
* Find an event by any custom query
*
* @param {object} query - any custom mongo query
* @return {Event}
*/
async findOneByQuery(query) {
const searchResult = await this.getCollection(this.TYPES.EVENTS)
.findOne(query);
return new Event(searchResult);
}
/**
* Returns events that grouped by day
*
* @param {Number} limit - events count limitations
* @param {Number} skip - certain number of documents to skip
* @param {'BY_DATE' | 'BY_COUNT'} sort - events sort order
* @param {EventsFilters} filters - marks by which events should be filtered
* @param {String} search - Search query
*
* @return {RecentEventSchema[]}
*/
async findRecent(
limit = 10,
skip = 0,
sort = 'BY_DATE',
filters = {},
search = ''
) {
if (typeof search !== 'string') {
throw new Error('Search parameter must be a string');
}
/**
* Check if pattern is safe RegExp
*/
if (!safe(search)) {
throw new Error('Invalid regular expression pattern');
}
const escapedSearch = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
limit = this.validateLimit(limit);
switch (sort) {
case 'BY_COUNT':
sort = 'count';
break;
case 'BY_DATE':
sort = 'lastRepetitionTime';
break;
case 'BY_AFFECTED_USERS':
sort = 'affectedUsers';
break;
default:
sort = 'lastRepetitionTime';
break;
}
const pipeline = [
{
$sort: {
groupingTimestamp: -1,
[sort]: -1,
},
},
];
const searchFilter = search.trim().length > 0
? {
$or: [
{
'event.payload.title': {
$regex: escapedSearch,
$options: 'i',
},
},
{
'event.payload.backtrace.file': {
$regex: escapedSearch,
$options: 'i',
},
},
{
'event.payload.context': {
$regex: escapedSearch,
$options: 'i',
},
},
],
}
: {};
const matchFilter = filters
? Object.fromEntries(
Object
.entries(filters)
.map(([mark, exists]) => [`event.marks.${mark}`, { $exists: exists } ])
)
: {};
pipeline.push(
{
$lookup: {
from: 'events:' + this.projectId,
localField: 'groupHash',
foreignField: 'groupHash',
as: 'event',
},
},
{
$unwind: '$event',
},
{
$match: {
...matchFilter,
...searchFilter,
},
},
{ $skip: skip },
{ $limit: limit },
{
$group: {
_id: null,
dailyInfo: { $push: '$$ROOT' },
events: { $push: '$event' },
},
},
{
$unset: 'dailyInfo.event',
}
);
const cursor = this.getCollection(this.TYPES.DAILY_EVENTS).aggregate(pipeline);
const result = (await cursor.toArray()).shift();
/**
* aggregation can return empty array so that
* result can be undefined
*
* for that we check result existence
*
* extra field `projectId` needs to satisfy GraphQL query
*/
if (result && result.events) {
result.events.forEach(event => {
event.projectId = this.projectId;
});
}
return result;
}
/**
* Fetch timestamps and total count of errors (or target error) for each day since
*
* @param {number} days - how many days we need to fetch for displaying in a chart
* @param {number} timezoneOffset - user's local timezone offset in minutes
* @param {string} groupHash - event's group hash for showing only target event
* @return {ProjectChartItem[]}
*/
async findChartData(days, timezoneOffset = 0, groupHash = '') {
const today = new Date();
const since = today.setDate(today.getDate() - days) / 1000;
/**
* Compose options for find method
* @type {{groupingTimestamp: {$gt: number}}}
*/
const options = {
groupingTimestamp: {
$gt: since,
},
};
/**
* Add eq check if groupHash was passed
*/
if (groupHash) {
options.groupHash = {
$eq: groupHash,
};
}
let dailyEvents = await this.getCollection(this.TYPES.DAILY_EVENTS)
.find(options)
.toArray();
/**
* Convert UTC midnight to midnights in user's timezone
*/
dailyEvents = dailyEvents.map((item) => {
return Object.assign({}, item, {
groupingTimestamp: getMidnightWithTimezoneOffset(item.lastRepetitionTime, item.groupingTimestamp, timezoneOffset),
});
});
/**
* Group events using 'groupingTimestamp:NNNNNNNN' key
* @type {ProjectChartItem[]}
*/
const groupedData = groupBy('groupingTimestamp')(dailyEvents);
/**
* Now fill all requested days
*/
let result = [];
for (let i = 0; i < days; i++) {
const now = new Date();
const day = new Date(now.setDate(now.getDate() - i));
const dayMidnight = getUTCMidnight(day) / 1000;
const groupedEvents = groupedData[`groupingTimestamp:${dayMidnight}`];
result.push({
timestamp: dayMidnight,
count: groupedEvents ? groupedEvents.reduce((sum, value) => sum + value.count, 0) : 0,
});
}
/**
* Order by time ascendance
*/
result = result.sort((a, b) => a.timestamp - b.timestamp);
return result;
}
/**
* Returns number of documents that occurred after the last visit time
*
* @param {Number} lastVisit - user's last visit time on project
*
* @return {Promise<Number>}
*
* @todo move to Project model
*/
async getUnreadCount(lastVisit) {
const query = {
'payload.timestamp': {
$gt: lastVisit,
},
};
return this.getCollection(this.TYPES.EVENTS)
.countDocuments(query);
}
/**
* Returns Event repetitions
*
* @param {string|ObjectID} eventId - Event's id
* @param {Number} limit - count limitations
* @param {Number} skip - selection offset
*
* @return {EventRepetitionSchema[]}
*
* @todo move to Repetitions(?) model
*/
async getEventRepetitions(eventId, limit = 10, skip = 0) {
limit = this.validateLimit(limit);
skip = this.validateSkip(skip);
/**
* Get original event
* @type {EventSchema}
*/
const eventOriginal = await this.findById(eventId);
/**
* Collect repetitions
* @type {EventRepetitionSchema[]}
*/
const repetitions = await this.getCollection(this.TYPES.REPETITIONS)
.find({
groupHash: eventOriginal.groupHash,
})
.sort({ _id: -1 })
.limit(limit)
.skip(skip)
.toArray();
const isLastPortion = repetitions.length < limit && skip === 0;
/**
* For last portion:
* add original event to the end of repetitions list
*/
if (isLastPortion) {
/**
* Get only 'repetitions' fields from event to fit Repetition scheme
* @type {EventRepetitionSchema}
*/
const firstRepetition = {
_id: eventOriginal._id,
payload: eventOriginal.payload,
groupHash: eventOriginal.groupHash,
};
repetitions.push(firstRepetition);
}
return repetitions;
}
/**
* Returns Event concrete repetition
*
* @param {String} repetitionId - id of Repetition to find
* @return {EventRepetitionSchema|null}
*
* @todo move to Repetitions(?) model
*/
async getEventRepetition(repetitionId) {
return this.getCollection(this.TYPES.REPETITIONS)
.findOne({
_id: ObjectID(repetitionId),
});
}
/**
* Return last occurrence of event
* @param {string} eventId - id of event to find repetition
* @return {EventRepetitionSchema|null}
*/
async getEventLastRepetition(eventId) {
const repetitions = await this.getEventRepetitions(eventId, 1);
if (repetitions.length === 0) {
return null;
}
return repetitions.shift();
}
/**
* Get a release from corresponding to this event
*
* @param {string} eventId - id of event to get the release
* @returns {Release|null}
*/
async getEventRelease(eventId) {
const eventOriginal = await this.findById(eventId);
const release = await mongo.databases.events.collection(this.TYPES.RELEASES).findOne({
release: eventOriginal.payload.release,
projectId: this.projectId.toString(),
});
return release;
}
/**
* Mark event as visited for passed user
*
* @param {string|ObjectId} eventId
* @param {string|ObjectId} userId
*
* @return {Promise<void>}
*/
async visitEvent(eventId, userId) {
return this.getCollection(this.TYPES.EVENTS)
.updateOne(
{ _id: new ObjectID(eventId) },
{ $addToSet: { visitedBy: new ObjectID(userId) } }
);
}
/**
* Mark or unmark event as Resolved, Ignored or Starred
*
* @param {string|ObjectId} eventId - event to mark
* @param {string} mark - mark label
*
* @return {Promise<void>}
*/
async toggleEventMark(eventId, mark) {
const collection = this.getCollection(this.TYPES.EVENTS);
const query = { _id: new ObjectID(eventId) };
const event = await collection.findOne(query);
const markKey = `marks.${mark}`;
let update;
if (event.marks && event.marks[mark]) {
update = {
$unset: { [markKey]: '' },
};
} else {
update = {
$set: { [markKey]: Math.floor(Date.now() / 1000) },
};
}
return collection.updateOne(query, update);
}
/**
* Remove all project events
*
* @return {Promise<void>}
*/
async remove() {
/**
* Check if collection is existing
* Drop collection only when it's existing
*/
if (await this.isCollectionExists(this.TYPES.EVENTS)) {
await this.getCollection(this.TYPES.EVENTS).drop();
}
if (await this.isCollectionExists(this.TYPES.DAILY_EVENTS)) {
await this.getCollection(this.TYPES.DAILY_EVENTS).drop();
}
if (await this.isCollectionExists(this.TYPES.REPETITIONS)) {
await this.getCollection(this.TYPES.REPETITIONS).drop();
}
}
/**
* Update assignee to selected event
*
* @param {string} eventId - event id
* @param {string} assignee - assignee id for this event
* @return {Promise<void>}
*/
async updateAssignee(eventId, assignee) {
const collection = this.getCollection(this.TYPES.EVENTS);
const query = { _id: new ObjectID(eventId) };
const update = {
$set: { assignee: assignee },
};
return collection.updateOne(query, update);
}
}
module.exports = EventsFactory;