UNPKG

2.11 kBJavaScriptView Raw
1const path = require('path');
2
3const Core = require("@knetik/micro-core");
4
5/**
6 *
7 * Each Job is configured with its own worker. The worker spawns threads as
8 * needed and processes job instances in the background. The worker function is
9 * transparent to the micro-core application and exists soulely to kick off the
10 * Job class' perform function in the correct customer context.
11 *
12 * Worker config should include only what is required for processing a Job.
13 * 1. *Do not include the queue adaptor in the worker env config.*
14 * 2. *Do not attempt to create jobs inside a job.*
15 *
16 * - reset config to the worker env `${NODE_ENV}-worker`
17 * - Core init
18 * - Core connect by app_id -> App
19 * - Get Job class from Adaptor.loadJobs
20 * - Call Job.perform
21 * - Returns the result of the job
22 *
23 * Keep in mind, We aren't handling errors. If you job crashes, we wont catch
24 * it. This is another reason for the multi threaded worker design. If the
25 * worker crashes, the micro core application does not.
26 *
27 * @name MicroQueueAdaptor#worker
28 */
29module.exports = job => {
30 const {
31 id,
32 name,
33 data: {
34 app: { app_id, token, request_id },
35 params
36 }
37 } = job;
38
39 const { APP_ROOT, NODE_ENV = "local" } = process.env;
40 const configPath = path.join(APP_ROOT, 'config', 'environments', NODE_ENV);
41
42 /* eslint import/no-dynamic-require: 0 */
43 const config = require(configPath);
44 process.env.NODE_ENV = NODE_ENV.match('worker') ? NODE_ENV : config.WORKER_ENV || `${NODE_ENV}/worker`;
45
46 const init = Core.initialized ? Promise.resolve.bind(Promise) : Core.init.bind(Core);
47
48 return init(process.cwd()).then(() => Core.connect(app_id, token, request_id)).then(App => {
49 App.Logger.info(`Performing Queued Job (${id})`, name, params);
50
51 const Adaptor = require("./index");
52 return Adaptor.loadJobs().then(jobs => {
53 const Job = jobs[name];
54
55 return Job.perform(App, params, job.progress.bind(job)).then(result => {
56 job.progress(100);
57 App.Logger.info(`Performing Queued Job (${id}): success`, name, result);
58
59 return result;
60 });
61 });
62 });
63};
\No newline at end of file