/
jobWrapper.js
329 lines (288 loc) · 9.64 KB
/
jobWrapper.js
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
/**
* Copyright (c) 2016, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or
* https://opensource.org/licenses/BSD-3-Clause
*/
/**
* /jobQueue/jobWrapper.js
*
* This jobWrapper module uses the "kue" library to help create jobs and
* enqueue them. Jobs are subsequently dequeued and executed by a separate
* worker process.
*/
'use strict'; // eslint-disable-line strict
const jobSetup = require('./setup');
const jobQueue = jobSetup.jobQueue;
const bulkDelSubQueue = jobSetup.bulkDelSubQueue;
const jwtUtil = require('../utils/jwtUtil');
const featureToggles = require('feature-toggles');
const activityLogUtil = require('../utils/activityLog');
const conf = require('../config');
const logJobCreate = require('./logJobCreate');
const jobType = require('./setup').jobType;
const queueTimeActivityLogs =
require('../clock/scheduledJobs/queueStatsActivityLogs');
// ttl converted to milliseconds
const TIME_TO_LIVE =
1000 * jobSetup.ttlForJobsAsync; // eslint-disable-line no-magic-numbers
/**
* Set log object params from job results.
*
* @param {Object} jobResultObj - Job result object
* @param {Object} logObject - Log object
*/
function mapJobResultsToLogObject(jobResultObj, logObject) {
const now = Date.now();
if (jobResultObj.reqStartTime) {
logObject.totalTime = `${now - jobResultObj.reqStartTime}ms`;
}
if (jobResultObj.jobEndTime) {
logObject.queueResponseTime = `${now - jobResultObj.jobEndTime}ms`;
}
if (jobResultObj.queueTime) {
logObject.queueTime = `${jobResultObj.queueTime}ms`;
}
if (jobResultObj.workTime) {
logObject.workTime = `${jobResultObj.workTime}ms`;
}
if (jobResultObj.dbTime) {
logObject.dbTime = `${jobResultObj.dbTime}ms`;
}
if (jobResultObj.recordCount) {
logObject.recordCount = jobResultObj.recordCount;
}
if (jobResultObj.errorCount) {
logObject.errorCount = jobResultObj.errorCount;
}
}
bulkDelSubQueue.on('completed', (job, jobResultObj) => {
const logObject = {
jobType: job.type,
jobId: job.id,
};
Object.assign(logObject, jobResultObj.requestInfo);
// when enableWorkerActivityLogs are enabled, update the logObject
if (featureToggles.isFeatureEnabled('enableWorkerActivityLogs') &&
jobResultObj && logObject) {
mapJobResultsToLogObject(jobResultObj, logObject);
// Update queueStatsActivityLogs
if (featureToggles
.isFeatureEnabled('enableQueueStatsActivityLogs')) {
queueTimeActivityLogs
.update(jobResultObj.recordCount, jobResultObj.queueTime);
}
/*
* The second argument should match the activity logging type in
* /config/activityLog.js
*/
activityLogUtil.printActivityLogString(logObject, 'worker');
}
});
/**
* Listen for a job completion event. If activity logs are enabled,
* update logObject and print log
*
* @param {Object} job - Job object to be cleaned up from the queue
* @param {Object} logObject - Object containing the information that needs to
* be logged.
*/
function processJobOnComplete(job, logObject) {
if (job) {
job.on('complete', (jobResultObj) => {
// when enableWorkerActivityLogs are enabled, update the logObject
if (featureToggles.isFeatureEnabled('enableWorkerActivityLogs') &&
jobResultObj && logObject) {
mapJobResultsToLogObject(jobResultObj, logObject);
// Update queueStatsActivityLogs
if (featureToggles
.isFeatureEnabled('enableQueueStatsActivityLogs')) {
queueTimeActivityLogs
.update(jobResultObj.recordCount, jobResultObj.queueTime);
}
/*
* The second argument should match the activity logging type in
* /config/activityLog.js
*/
activityLogUtil.printActivityLogString(logObject, 'worker');
}
});
}
} // processJobOnComplete
/**
* If req object is defined; extract the user name, token and ipaddress and
* return the object with details.
* @param req - Request object
*/
function getRequestInfo(req) {
const reqInfo = {};
/*
* If req object is defined; extract the user name, token and ipaddress and
* update the log object. Add "request_id" if available.
*/
if (req) {
if (req.request_id) reqInfo.request_id = req.request_id;
reqInfo.ipAddress = req.locals.ipAddress;
/*
* we already set UserName and TokenName in req headers when verifying
* token
*/
reqInfo.user = req.headers.UserName;
reqInfo.token = req.headers.TokenName;
reqInfo.process = req.process;
}
return reqInfo;
}
/**
* Logs worker activity when complete.
*
* @param {Object} req - Request object
* @param {Object} job - Worker job
*/
function logJobOnComplete(req, job) {
// if activity logs are enabled, log activity info
if (featureToggles.isFeatureEnabled('enableWorkerActivityLogs')) {
// create worker activity log object
const logObject = {};
if (job.type) {
logObject.jobType = job.type;
}
if (job.id) {
logObject.jobId = job.id;
}
/*
* If req object is defined; extract the user name, token and ipaddress and
* update the log object. Add "request_id" if available.
*/
if (req) {
if (req.request_id) logObject.request_id = req.request_id;
logObject.ipAddress = req.locals.ipAddress;
/*
* we already set UserName and TokenName in req headers when verifying
* token
*/
logObject.user = req.headers.UserName;
logObject.token = req.headers.TokenName;
logObject.process = req.process;
}
// continue to update and print logObject on job completion.
processJobOnComplete(job, logObject);
}
}
/**
* Prioritize jobs based on user name, token name or ip address.
*
* @param {Array} prioritize - array of user names, token names and/or ip
* addresses to prioritize
* @param {Array} deprioritize - array of user names, token names and/or ip
* addresses to deprioritize
* @param {Object} req - the request object
* @returns {String|Integer} kue priority or Bull priority
*/
function calculateJobPriority(prioritize, deprioritize, req) {
const jobPriority = {
high: 'high',
normal: 'normal',
low: 'low',
};
if (featureToggles.isFeatureEnabled('enableBullForBulkDelSubj')) {
// ranges from 1 (highest priority) to MAX_INT (lowest priority)
jobPriority.high = 1;
jobPriority.normal = 50;
jobPriority.low = 100;
}
// low=10, normal=0, medium=-5, high=-10, critical=-15
if (!req) return jobPriority.normal;
const ip = req.locals.ipAddress;
const un = req.headers.UserName || '';
const tn = req.headers.TokenName || '';
if (prioritize.includes(ip) ||
prioritize.includes(un) ||
prioritize.includes(tn)) return jobPriority.high;
if (deprioritize.includes(ip) ||
deprioritize.includes(un) ||
deprioritize.includes(tn)) return jobPriority.low;
return jobPriority.normal;
} // calculateJobPriority
/**
* This is a promisified version of the createJob function which resolves to
* the job created and saved by the Kue api.
*
* @param {String} jobName - The job name. A worker process will be
* listening for this jobName to process the jobs.
* @param {Object} data - Data for the job to work with.
* @param {Object} req - Request object.
* @returns {Promise} - resolves to job object. The job object will be null
* when the jobQueue is created in test mode.
*/
function createPromisifiedJob(jobName, data, req) {
const startTime = Date.now();
if (featureToggles.isFeatureEnabled('enableBullForBulkDelSubj') &&
jobName === jobType.bulkDeleteSubjects) {
data.requestInfo = getRequestInfo(req);
const jobPriority = calculateJobPriority(conf.prioritizeJobsFrom,
conf.deprioritizeJobsFrom, req);
return bulkDelSubQueue.add(data, { priority: jobPriority })
.then((job) => {
job.type = jobType.bulkDeleteSubjects;
logJobCreate(startTime, job);
return job;
});
}
const jobPriority = calculateJobPriority(conf.prioritizeJobsFrom,
conf.deprioritizeJobsFrom, req);
return new Promise((resolve, reject) => {
const job = jobQueue.create(jobName, data);
job.ttl(TIME_TO_LIVE)
.priority(jobPriority)
.save((err) => {
if (err) {
const msg =
`Error adding ${jobName} job (id ${job.id}) to the worker queue`;
return reject(msg);
}
logJobOnComplete(req, job);
logJobCreate(startTime, job);
return resolve(job);
});
});
} // createPromisifiedJob
/**
* Creates a job to be processed using the KUE api, given the jobName and
* data to be processed by the job.
*
* @param {String} jobName - The job name. A worker process will be
* listening for this jobName to process the jobs.
* @param {Object} data - Data for the job to work with.
* @param {Object} req - Request object.
* @returns {Object} - A job object. The job object will be null when the
* jobQueue is created in the test mode.
*/
function createJob(jobName, data, req) {
const startTime = Date.now();
const jobPriority = calculateJobPriority(conf.prioritizeJobsFrom,
conf.deprioritizeJobsFrom, req);
const job = jobQueue.create(jobName, data);
job.ttl(TIME_TO_LIVE)
.priority(jobPriority)
.save((err) => {
if (err) {
const msg =
`Error adding ${jobName} job (id ${job.id}) to the worker queue`;
throw new Error(msg);
}
logJobOnComplete(req, job);
logJobCreate(startTime, job);
});
return job;
} // createJob
module.exports = {
calculateJobPriority, // export for testing only
createJob,
createPromisifiedJob,
jobQueue,
logJobOnComplete,
mapJobResultsToLogObject,
bulkDelSubQueue,
}; // exports