-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproject.js
More file actions
549 lines (478 loc) · 17.3 KB
/
project.js
File metadata and controls
549 lines (478 loc) · 17.3 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
import { ReceiveTypes } from '@hawk.so/types';
import * as telegram from '../utils/telegram';
const mongo = require('../mongo');
const { ApolloError, UserInputError } = require('apollo-server-express');
const Validator = require('../utils/validator');
const UserInProject = require('../models/userInProject');
const EventsFactory = require('../models/eventsFactory');
const getEventsFactory = require('./helpers/eventsFactory').default;
const ProjectToWorkspace = require('../models/projectToWorkspace');
const { dateFromObjectId } = require('../utils/dates');
const ProjectModel = require('../models/project').default;
const EVENTS_GROUP_HASH_INDEX_NAME = 'groupHashUnique';
const REPETITIONS_GROUP_HASH_INDEX_NAME = 'groupHash_hashed';
const REPETITIONS_USER_ID_INDEX_NAME = 'userId';
const EVENTS_TIMESTAMP_INDEX_NAME = 'timestamp';
const GROUPING_TIMESTAMP_INDEX_NAME = 'groupingTimestamp';
const GROUPING_TIMESTAMP_AND_GROUP_HASH_INDEX_NAME = 'groupingTimestampAndGroupHash';
const MAX_SEARCH_QUERY_LENGTH = 50;
/**
* See all types and fields here {@see ../typeDefs/project.graphql}
*/
module.exports = {
Query: {
/**
* Returns project's Model
* @param {ResolverObj} _obj
* @param {String} projectId - project id
* @param {ContextFactories} factories - factories for working with models
* @return {Promise<ProjectDBScheme>}
*/
async project(_obj, { projectId }, { factories }) {
return factories.projectsFactory.findById(projectId);
},
},
Mutation: {
/**
* Creates project
*
* @param {ResolverObj} _obj
* @param {string} workspaceId - workspace ID
* @param {string} name - project name
* @param {string} image - project logo
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
* @return {Project[]}
*/
async createProject(_obj, { workspaceId, name, image }, { user, factories }) {
const workspace = await factories.workspacesFactory.findById(workspaceId);
if (!workspace) {
throw new UserInputError('No such workspace');
}
const options = {
name,
workspaceId,
uidAdded: user.id,
image,
};
let project = await factories.projectsFactory.create(options);
const userData = await factories.usersFactory.findById(user.id);
try {
await project.createNotificationsRule({
uidAdded: user.id,
isEnabled: true,
whatToReceive: ReceiveTypes.SEEN_MORE,
including: [],
excluding: [],
threshold: 20,
thresholdPeriod: 3600000,
channels: {
email: {
isEnabled: true,
endpoint: userData.email,
minPeriod: 60,
},
telegram: {
isEnabled: false,
endpoint: '',
minPeriod: 60,
},
slack: {
isEnabled: false,
endpoint: '',
minPeriod: 60,
},
},
}, true);
project = await factories.projectsFactory.findById(project._id);
} catch (err) {
telegram.sendMessage(`❌ Failed to enable default notifications for project ${name}`);
}
/**
* Create collections for storing events and setup indexes
*/
const projectEventsCollection = await mongo.databases.events.createCollection('events:' + project._id);
const projectRepetitionsEventsCollection = await mongo.databases.events.createCollection('repetitions:' + project._id);
const projectDailyEventsCollection = await mongo.databases.events.createCollection('dailyEvents:' + project._id);
await projectDailyEventsCollection.createIndex({
groupingTimestamp: 1,
}, {
name: GROUPING_TIMESTAMP_INDEX_NAME,
});
await projectDailyEventsCollection.createIndex({
groupingTimestamp: 1,
groupHash: 1,
}, {
name: GROUPING_TIMESTAMP_AND_GROUP_HASH_INDEX_NAME,
});
await projectEventsCollection.createIndex({
groupHash: 1,
},
{
unique: true,
name: EVENTS_GROUP_HASH_INDEX_NAME,
});
await projectRepetitionsEventsCollection.createIndex({
groupHash: 'hashed',
},
{
name: REPETITIONS_GROUP_HASH_INDEX_NAME,
});
await projectRepetitionsEventsCollection.createIndex({
'payload.user.id': 1,
}, {
name: REPETITIONS_USER_ID_INDEX_NAME,
sparse: true,
});
await projectEventsCollection.createIndex({
timestamp: 1,
}, {
name: EVENTS_TIMESTAMP_INDEX_NAME,
sparse: true,
});
telegram.sendMessage(`🤯 Project ${name} was created`);
return project;
},
/**
* Update project settings
*
* @param {ResolverObj} _obj
* @param {string} projectId - id of the updated project
* @param {string} name - project name
* @param {string} description - project description
* @param {string} - project logo
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
*
* @returns {Project}
*/
async updateProject(_obj, { id, name, description, image }, { user, factories }) {
if (!Validator.string(name)) {
throw new UserInputError('Invalid name length');
}
if (!Validator.string(description, 0)) {
throw new UserInputError('Invalid description length');
}
const project = await factories.projectsFactory.findById(id);
if (!project) {
throw new ApolloError('There is no project with that id');
}
if (project.workspaceId.toString() === '6213b6a01e6281087467cc7a') {
throw new ApolloError('Unable to update demo project');
}
try {
const options = {
name,
description,
};
if (image) {
options.image = image;
}
return project.updateProject(options);
} catch (err) {
throw new ApolloError('Something went wrong');
}
},
/**
* Update project rate limits settings
*
* @param {ResolverObj} _obj
* @param {string} id - project id
* @param {Object | null} rateLimitSettings - rate limit settings (null to remove)
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
*
* @returns {Project}
*/
async updateProjectRateLimits(_obj, { id, rateLimitSettings }, { user, factories }) {
const project = await factories.projectsFactory.findById(id);
if (!project) {
throw new ApolloError('There is no project with that id');
}
if (project.workspaceId.toString() === '6213b6a01e6281087467cc7a') {
throw new ApolloError('Unable to update demo project');
}
// Validate rate limit settings if provided
if (rateLimitSettings) {
const { N, T } = rateLimitSettings;
// Validate that N and T exist
if (!N || !T) {
throw new UserInputError(
'Rate limit settings must contain both N (threshold) and T (period) fields.'
);
}
// Validate N (threshold) - must be positive integer > 0
if (typeof N !== 'number' || !Number.isInteger(N) || N <= 0) {
throw new UserInputError(
'Invalid rate limit threshold. Must be a positive integer greater than 0.'
);
}
// Validate T (period) - must be positive integer >= 60 (1 minute)
if (typeof T !== 'number' || !Number.isInteger(T) || T < 60) {
throw new UserInputError(
'Invalid rate limit period. Must be a positive integer greater than or equal to 60 seconds.'
);
}
// Validate reasonable maximums (prevent extremely large values)
const MAX_THRESHOLD = 1000000000; // 1 billion
const MAX_PERIOD = 60 * 60 * 24 * 31; // 1 month in seconds
if (N > MAX_THRESHOLD) {
throw new UserInputError(
`Rate limit threshold cannot exceed ${MAX_THRESHOLD.toLocaleString()}.`
);
}
if (T > MAX_PERIOD) {
throw new UserInputError(
`Rate limit period cannot exceed ${MAX_PERIOD.toLocaleString()} seconds (1 month).`
);
}
}
try {
return project.updateProject({
rateLimitSettings: rateLimitSettings || null,
});
} catch (err) {
throw new ApolloError('Failed to update project rate limit settings', { originalError: err });
}
},
/**
* Generates new project integration token by id
*
* @param {ResolverObj} _obj - default resolver object
* @param {string} id - id of the project in which the token field is being regenerated
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
*
* @returns {Object}
*/
async generateNewIntegrationToken(_obj, { id }, { factories }) {
const project = await factories.projectsFactory.findById(id);
if (!project) {
throw new ApolloError('There is no project with that id:', id);
}
const integrationId = project.integrationId || ProjectModel.generateIntegrationId();
const encodedIntegrationToken = ProjectModel.generateIntegrationToken(integrationId);
try {
const updatedProject = await project.updateProject({
token: encodedIntegrationToken,
integrationId,
});
return {
recordId: updatedProject._id,
record: updatedProject,
};
} catch (err) {
throw new ApolloError('Can\'t update integration token', err);
}
},
/**
* Remove project
*
* @param {ResolverObj} _obj
* @param {string} projectId - id of the updated project
* @param {UserInContext} user - current authorized user {@see ../index.js}
* @param {ContextFactories} factories - factories for working with models
*
* @returns {Promise<boolean>}
*/
async removeProject(_obj, { projectId }, { user, factories }) {
const project = await factories.projectsFactory.findById(projectId);
if (!project) {
throw new ApolloError('There is no project with that id');
}
if (project.workspaceId.toString() === '6213b6a01e6281087467cc7a') {
throw new ApolloError('Unable to remove demo project');
}
const workspaceModel = await factories.workspacesFactory.findById(project.workspaceId.toString());
/**
* Remove project events
*/
await new EventsFactory(project._id).remove();
/**
* Remove project from workspace
*/
await new ProjectToWorkspace(workspaceModel._id.toString()).remove(project._id);
/**
* Remove project
*/
await project.remove();
return true;
},
/**
* Updates user visit time on project and returns it
*
* @param {ResolverObj} _obj
* @param {String} projectId - project ID
* @param {Context.user} user - current authorized user {@see ../index.js}
* @return {Promise<Number>}
*/
async updateLastProjectVisit(_obj, { projectId }, { user }) {
const userInProject = new UserInProject(user.id, projectId);
return userInProject.updateLastVisit();
},
},
Project: {
/**
* Returns project creation date
*
* @param {ProjectDBScheme} project - result of parent resolver
*
* @returns {Date}
*/
creationDate(project) {
return dateFromObjectId(project._id);
},
/**
* Find project's event
*
* @param {ProjectDBScheme} project - result of parent resolver
* @param {String} eventId - event's identifier
* @param {String} originalEventId - id of the original event
*
* @returns {EventRepetitionSchema}
*/
async event(project, { eventId: repetitionId, originalEventId }, context) {
const factory = getEventsFactory(context, project._id);
const repetition = await factory.getEventRepetition(repetitionId, originalEventId);
if (!repetition) {
return null;
}
repetition.projectId = project._id;
return repetition;
},
/**
* Find project events
*
* @param {ProjectDBScheme} project - result of parent resolver
* @param {number} limit - query limit
* @param {number} skip - query skip
* @param {Context.user} user - current authorized user {@see ../index.js}
* @returns {Event[]}
*/
async events(project, { limit, skip }, context) {
const factory = getEventsFactory(context, project._id);
return factory.find({}, limit, skip);
},
/**
* Returns events count that wasn't seen on project
*
* @param {ProjectDBScheme} project - result of parent resolver
* @param {Object} data - additional data. In this case it is empty
* @param {User} user - authorized user
*
* @return {Promise<number>}
*/
async unreadCount(project, data, { user, ...context }) {
const eventsFactory = getEventsFactory(context, project._id);
const userInProject = new UserInProject(user.id, project._id);
const lastVisit = await userInProject.getLastVisit();
return eventsFactory.getUnreadCount(lastVisit);
},
/**
* Returns recent Events grouped by day
*
* @param {ProjectDBScheme} project - result of parent resolver
* @param {Number} limit - limit for events count
* @param {DailyEventsCursor} cursor - object with boundary values of the first event in the next portion
* @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 {Promise<RecentEventSchema[]>}
*/
async dailyEventsPortion(project, { limit, nextCursor, sort, filters, search }, context) {
if (search) {
if (search.length > MAX_SEARCH_QUERY_LENGTH) {
search = search.slice(0, MAX_SEARCH_QUERY_LENGTH);
}
}
const factory = getEventsFactory(context, project._id);
const dailyEventsPortion = await factory.findDailyEventsPortion(limit, nextCursor, sort, filters, search);
return dailyEventsPortion;
},
/**
* Returns data about how many events accepted at each of passed N days
*
* @param {ProjectDBScheme} project - result of parent resolver
* @param {Number} days - how many days we need to fetch for displaying in a charts
* @param {number} timezoneOffset - user's local timezone offset in minutes
*
* @return {Promise<ProjectChartItem[]>}
*/
async chartData(project, { startDate, endDate, groupBy, timezoneOffset }, context) {
const factory = getEventsFactory(context, project._id);
return factory.getChartData(startDate, endDate, groupBy, timezoneOffset, project._id);
},
/**
* Returns list of not archived releases with number of events that were introduced in this release
* We count events as new, cause payload.release only contain the same release name if the event is original
*
* @param {ProjectDBScheme} project - result of parent resolver
* @returns {Promise<Array<{release: string, timestamp: number, newEventsCount: number, commitsCount: number, filesCount: number}>>}
*/
async releases(project) {
const releasesCollection = mongo.databases.events.collection('releases');
const pipeline = [
{ $match: { projectId: project._id.toString() } },
{
$project: {
release: {
$convert: {
input: '$release',
to: 'string',
onError: '',
onNull: '',
},
},
commitsCount: { $size: { $ifNull: ['$commits', [] ] } },
filesCount: { $size: { $ifNull: ['$files', [] ] } },
_releaseIdSec: { $floor: { $divide: [ { $toLong: { $toDate: '$_id' } }, 1000] } },
},
},
{
$lookup: {
from: 'events:' + project._id,
let: { rel: '$release' },
pipeline: [
{
$match: {
$expr: {
$eq: [ {
$convert: {
input: '$payload.release',
to: 'string',
onError: '',
onNull: '',
},
}, '$$rel'],
},
},
},
{
$group: {
_id: null,
count: { $sum: 1 },
},
},
],
as: 'eventAgg',
},
},
{
$project: {
_id: 0,
release: 1,
commitsCount: 1,
filesCount: 1,
newEventsCount: { $ifNull: [ { $arrayElemAt: ['$eventAgg.count', 0] }, 0] },
timestamp: '$_releaseIdSec',
},
},
{ $sort: { _id: -1 } },
];
const cursor = releasesCollection.aggregate(pipeline);
const result = await cursor.toArray();
return result;
},
},
};