dcp-worker 4.1.1 → 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,23 +1,31 @@
1
1
  /**
2
- * @file worker-loggers/dashboard.js
3
- * @author Ryan Rossiter, ryan@kingsds.network
4
- * @date April 2020
5
- * @author Wes Garland, wes@distributive.network
6
- * @date June 2023
2
+ * @file dashboard-console.js
3
+ * @author Ryan Rossiter, ryan@kingsds.network
4
+ * @date April 2020
5
+ * @author Wes Garland, wes@distributive.network
6
+ * @date June 2023, June 2025
7
7
  *
8
- * This module uses the blessed library to create a monitoring dashboard for the worker.
9
- * A corresponding worker-logger, dashboard.js, knows how to log to this dashboard.
8
+ * This module uses the blessed library to create a monitoring dashboard for the worker. The init
9
+ * function returns a console object which knows how to log to this dashboard. The console's close
10
+ * method destroys the dashboard and dumps recent log messages to stdout/stderr.
10
11
  */
11
12
  'use strict';
12
13
 
14
+ const process = require('process');
15
+ const debug = require('debug');
13
16
  const dcpConfig = require('dcp/dcp-config');
17
+ const wallet = require('dcp/wallet');
14
18
  const chalk = require('chalk');
15
19
  const blessed = require('blessed');
16
20
  const contrib = require('blessed-contrib');
17
- const components = require('./blessed-components');
18
- const utils = require('../lib/utils');
21
+ const components = require('../blessed-components');
22
+ const utils = require('../utils');
19
23
 
20
- const { replaceWorkerEventHandler, replaceSandboxEventHandler, newSandboxCallbacks } = require('./default-ui-events');
24
+ const { Console } = require('console');
25
+ const { RingBuffer } = require('dcp/utils');
26
+ const { logLevels } = require('../consts');
27
+
28
+ const { replaceWorkerEventHandler, replaceSandboxEventHandler, newSandboxCallbacks } = require('../default-ui-events')
21
29
  const systemStateInfo = globalThis.systemStateInfo;
22
30
 
23
31
  const SLICE_FETCH_STATUS = {
@@ -31,38 +39,55 @@ const usingDebugger = require('module')._cache.niim instanceof require('module')
31
39
  const screenConf = {
32
40
  input: usingDebugger ? new (require('events').EventEmitter) : undefined,
33
41
  output: usingDebugger ? new (require('events').EventEmitter) : undefined,
42
+ debug: false,
43
+ log: process.env.DCP_WORKER_BLESSED_DASHBOARD_LOG || undefined,
44
+ dump: Boolean(process.env.DCP_WORKER_BLESSED_DASHBOARD_LOG),
45
+ smartCSR: true,
34
46
  };
47
+ const closeLogDumpSize = Number(process.env.DCP_WORKER_DASHBOARD_PRESERVE_LOG_LINES) || 30; /* Dump this many log messages when .close method invoked */
48
+
49
+ var screen; /* top-level tui handle */
50
+ var logPane; /* where console.log etc messages are displayed */
51
+ var sandboxPane; /* where live info about sandboxes is displayed */
52
+ var workerInfoPane; /* where mostly-static info about the worker is displayed */
53
+ var sliceFetchStatus = SLICE_FETCH_STATUS.IDLE;
54
+ var totalDCCs = 0;
55
+ var lastTask;
56
+
35
57
  /**
36
- * Initialize the blessed dashboard
37
- * @param {Worker} worker Reference to the DCP Worker
38
- * @param {object} options Options which may affect behaviour. Not currently used.
58
+ * Send a signal to the caller
59
+ * @param {number|string} sig the signal to raise
39
60
  */
40
- exports.init = function dashboard$$init(worker, options, bannerLogCumulative)
61
+ function raise(sig)
41
62
  {
42
- var sliceFetchStatus = SLICE_FETCH_STATUS.IDLE;
43
- var totalDCCs = 0;
44
- var screen = blessed.screen(screenConf);
63
+ if (sig === 'SIGESC') /* synthetic */
64
+ process.emit(sig, sig);
65
+ else
66
+ process.kill(process.pid, sig);
67
+ }
45
68
 
46
- worker.on('end', () => {
47
- if (screen?.destroy)
48
- screen.destroy();
49
- screen.destroy = false;
50
- });
51
- process.on('exit', () => {
52
- if (screen?.destroy)
53
- screen.destroy();
54
- });
69
+ /**
70
+ * Initialize the blessed dashboard console.
71
+ */
72
+ function createDashboard()
73
+ {
74
+ globalThis.screen = screen = blessed.screen(screenConf);
75
+
76
+ /* Add redraw method - move cursor to home position, replay screenshot without trailing \n */
77
+ screen.redraw = function screen$$redraw() {
78
+ process.stdout.write('\u001b[H' + this.screenshot().slice(0,-1));
79
+ }
55
80
 
56
81
  const grid = new contrib.grid({ rows: 3, cols: 6, screen }); // eslint-disable-line new-cap
57
- const workerInfoPane = grid.set(2, 0, 1, 6, components.log, {
82
+ workerInfoPane = grid.set(2, 0, 1, 6, components.log, {
58
83
  label: 'Worker Status',
59
84
  scrollbar: { bg: 'blue' },
60
85
  });
61
- const logPane = grid.set(0, 2, 2, 4, components.log, {
86
+ logPane = grid.set(0, 2, 2, 4, components.log, {
62
87
  label: 'Worker Log',
63
88
  scrollbar: { bg: 'blue' },
64
89
  });
65
- const sandboxPane = grid.set(0, 0, 2, 2, components.sandboxPaneFactory, {
90
+ sandboxPane = grid.set(0, 0, 2, 2, components.sandboxPaneFactory, {
66
91
  label: 'Sandboxes',
67
92
  scrollable: true,
68
93
  alwaysScroll: true,
@@ -87,8 +112,8 @@ exports.init = function dashboard$$init(worker, options, bannerLogCumulative)
87
112
  hidden: true,
88
113
  });
89
114
 
90
- global.tui = { workerInfoPane, logPane, sandboxPane, screen, grid, passwordBox };
91
- let lastTask;
115
+ if (usingDebugger)
116
+ globalThis.tui = { workerInfoPane, logPane, sandboxPane, screen, grid, passwordBox };
92
117
 
93
118
  function askPassword(promptMessage)
94
119
  {
@@ -116,20 +141,32 @@ exports.init = function dashboard$$init(worker, options, bannerLogCumulative)
116
141
  return askPassword(promptMessage);
117
142
  };
118
143
 
119
- delete exports.init; /* singleton */
120
- console.log(' . Starting dashboard and redirecting logs');
121
- if (!usingDebugger)
122
- exports.logPane = logPane; /* now dashboard log can find the pane */
123
- for (let args of bannerLogCumulative) /* re-draw previously-emited log lines as screen has cleared */
124
- logPane.log(...args);
125
- setInterval(() => screen.render(), 2000).unref(); /* ensure we didn't forget to render an important update */
126
- updateWorkerInfo();
127
-
128
144
  /* Apply key bindings which mimic canonical input mode */
129
- screen.key(['C-c'], () => raise('SIGINT'));
130
- screen.key(['C-z'], () => raise('SIGTSTP'));
145
+ screen.key(['C-c'], () => raise('SIGINT'));
146
+ screen.key(['C-z'], () => raise('SIGTSTP'));
131
147
  screen.key(['\u001c'], () => raise('SIGQUIT')); /* C-\ */
132
- screen.key(['escape'], () => raise('SIGINT'));
148
+ screen.key(['escape'], () => raise('SIGESC'));
149
+ screen.key(['C-l'], () => screen.redraw());
150
+
151
+ /* Try to restore the dashboard after ^Z */
152
+ process.on('SIGCONT', () => {
153
+ if (!usingDebugger)
154
+ {
155
+ process.stdin.setRawMode(false);
156
+ process.stdin.setRawMode(true);
157
+ }
158
+ screen.render();
159
+ screen.redraw();
160
+ });
161
+ }
162
+
163
+ function setWorker(worker)
164
+ {
165
+ const identity = require('dcp/identity');
166
+
167
+ console.log(' . Starting dashboard');
168
+ setInterval(() => screen.render(), 2000).unref(); /* ensure we didn't forget to render an important update */
169
+ updateWorkerInfo();
133
170
 
134
171
  setInterval(updateWorkerInfo, 1000).unref();
135
172
  function updateWorkerInfo(fetchInfo)
@@ -151,7 +188,7 @@ exports.init = function dashboard$$init(worker, options, bannerLogCumulative)
151
188
  gpuInfo = chalk.cyan(systemStateInfo.gpu.device);
152
189
  }
153
190
  else
154
- gpuInfo = chalk.red(`error detecting`);
191
+ gpuInfo = chalk.red('error detecting');
155
192
 
156
193
  workerInfoPane.setLabel(`Worker Status [${sliceFetchStatus}]`);
157
194
  workerInfoPane.setContent([
@@ -159,19 +196,19 @@ exports.init = function dashboard$$init(worker, options, bannerLogCumulative)
159
196
  '',
160
197
  ` Scheduler: ${chalk.yellow(dcpConfig.scheduler.location.href)}`,
161
198
  ` Bank: ${chalk.yellow(dcpConfig.bank.location.href)}`,
162
- ` Bank Account: ${chalk.yellow(worker.paymentAddress || 'Starting...')}`,
163
- ` Identity: ${chalk.yellow(worker.identityKeystore? worker.identityKeystore.address : 'Starting...')}`,
199
+ ` Bank Account: ${chalk.yellow(worker.config.paymentAddress)}`,
200
+ ` Identity: ${chalk.yellow(identity.get().address)}`,
164
201
  ` GPU: ${gpuInfo}`,
165
202
  ` Jobs: ${worker.config.jobIds?.length ? worker.config.jobIds.join(', ') : '<any>'}`,
166
- ` Compute Groups: ${Object.keys(worker.config.computeGroups).length + (worker.config.leavePublicGroup ? 0 : 1)}`,
167
- `Global Compute Group: ${worker.config.leavePublicGroup ? 'no' : 'yes'}`,
203
+ ` Compute Groups: ${Object.keys(worker.config.computeGroups).length + (worker.config.leaveGlobalGroup ? 0 : 1)}`,
204
+ `Global Compute Group: ${worker.config.leaveGlobalGroup ? 'no' : 'yes'}`,
168
205
  ` Worker Id: ${worker.id}`,
169
206
  ` Current Time: ${new Date(Date.now()).toUTCString()}`,
170
- ` Last Task Request: ${lastTask ? new Date(lastTask.fetchStart).toUTCString() : 0}`,
171
- ` Slices in task: ${lastTask ? Object.values(lastTask.slices).reduce((acc, val) => acc + val, 0) : 0}`,
172
- ` Jobs in task: ${lastTask ? Object.keys(lastTask.jobs).length : 0}`,
207
+ ` Last Task Request: ${lastTask?.fetchStart ? new Date(lastTask.fetchStart).toUTCString() : '-'}`,
208
+ ` Slices in task: ${lastTask?.slices ? Object.values(lastTask.slices).reduce((acc, val) => acc + val, 0) : '-'}`,
209
+ ` Jobs in task: ${lastTask?.jobs ? Object.keys(lastTask.jobs).length : '-'}`,
173
210
  ].join('\n'));
174
- screen.render();
211
+ screen && screen.render();
175
212
  }
176
213
 
177
214
  /* Override default event behaviour to work better with the Dashboard. */
@@ -270,13 +307,86 @@ exports.init = function dashboard$$init(worker, options, bannerLogCumulative)
270
307
  sandboxPane.update();
271
308
  updateWorkerInfo();
272
309
  });
273
- };
310
+ }
274
311
 
275
312
  /**
276
- * Send a signal to the caller
277
- * @param {number|string} sig the signal to raise
313
+ * Initialize the the TUI, then make a new console object for stdio and override the individual methods
314
+ * so that they display on the TUI log pane. Console messages which go to the TUI are also buffered in
315
+ * ring buffer, which is allows us to dump the most recent log messages to stdout/stderr when destroying
316
+ * the console.
278
317
  */
279
- function raise(sig)
318
+ exports.init = function dashboardConsole$$Init()
319
+ {
320
+ const console = new Console(process);
321
+ const logHistory = new RingBuffer(closeLogDumpSize);
322
+ const inspect = Symbol.for('nodejs.util.inspect.custom');
323
+
324
+ createDashboard();
325
+
326
+ function consoleMethodFactory(logLevel)
327
+ {
328
+ return function dashboardConsoleMethodImpl() {
329
+ const argv = Array.from(arguments);
330
+ logHistory.push({ logLevel, argv: argv.slice() });
331
+ for (let i in argv)
332
+ {
333
+ if (argv[i] instanceof wallet.Address)
334
+ argv[i] = chalk.grey(String(argv[i]));
335
+ else if (argv[i] instanceof Error || (typeof argv[i] === 'object' && argv[i][inspect]))
336
+ argv[i] = require('node:util').inspect(argv[i]);
337
+ else if (logLevel === 'error' && typeof argv[i] === 'string')
338
+ argv[i] = chalk.red(argv[i]);
339
+ }
340
+ logPane.log(...argv);
341
+ }
342
+ }
343
+
344
+ for (let level of Object.values(logLevels))
345
+ console[level] = consoleMethodFactory(level);
346
+
347
+ /**
348
+ * throb API: calls with arguments set facility and message. First call without argument emits the
349
+ * message. All calls without arguments advance the throbber.
350
+ */
351
+ console.throb = function dashboardConsole$$throb(...args)
352
+ {
353
+ const throb = dashboardConsole$$throb;
354
+ var throbPos = throb.pos || 0;
355
+ if (args.length)
356
+ logPane.log(...args);
357
+ const throbChars = '/-\\|';
358
+ throb.pos = throbPos = (throbPos + 1) % throbChars.length;
359
+ logPane.advanceThrob(throbChars[throbPos]);
360
+ }
361
+
362
+ /**
363
+ * Destroy the dashboard, then dump the most recent lines back to stdout/stderr.
364
+ */
365
+ console.close = function dashboardConsole$$close()
366
+ {
367
+ if (screen?.destroy)
368
+ screen.destroy();
369
+ screen = false;
370
+
371
+ const stdioConsole = new (require('console').Console)(process);
372
+ if (logHistory.count > logHistory.size)
373
+ process.stdout.write(chalk.grey('---' + ' \u2702 -'.repeat(15) + '--\n'));
374
+ logHistory.forEach(entry => {
375
+ const { logLevel, argv } = entry;
376
+ stdioConsole[logLevel](...argv);
377
+ });
378
+ }
379
+
380
+ console.setWorker = setWorker;
381
+
382
+ debug('dcp-worker:console')('Initialized dashboard console');
383
+ return console;
384
+ }
385
+
386
+ /**
387
+ * Symbols shared only with "friends" of dashboard-console
388
+ */
389
+ exports.getFriendSymbols = function dashboardConsole$$getFriendSymbols()
280
390
  {
281
- process.kill(process.pid, sig);
391
+ return { screen, logPane }
282
392
  }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @file worker-consoles/index.js
3
+ * Implementation of the setConsoleType method, which replaces the global console object.
4
+ * That, in turn, allows dcp library code (eg the supervisor) to have access to the user
5
+ * operating and troubleshooting the worker.
6
+ *
7
+ * The console object is an abstraction of the "right in front of me" user interface. In
8
+ * addition to logging functions, it also has the following methods:
9
+ * - setWorker: tell the console about the worker object
10
+ * - throb: display/advance a throbber
11
+ * - close: restore the default console
12
+ *
13
+ * @author Wes Garland, wes@distributive.network
14
+ * @date June 2025
15
+ */
16
+ 'use strict';
17
+
18
+ const path = require('path');
19
+ const debug = require('debug');
20
+
21
+ exports.setConsoleType = setConsoleType;
22
+
23
+ function setConsoleType(consoleType)
24
+ {
25
+ var consoleImpl;
26
+ debug('dcp-worker:console')('set console type to', consoleType);
27
+
28
+ try
29
+ {
30
+ consoleType = path.basename(consoleType); /* ensure no .. */
31
+ consoleImpl = require(`./${consoleType}-console`);
32
+ }
33
+ catch (error)
34
+ {
35
+ if (error.code === 'MODULE_NOT_FOUND')
36
+ {
37
+ const errorMessageStart = error.message.replace(/\n.*/g, '');
38
+ error.message = `Unknown console type '${consoleType}' (${errorMessageStart})`;
39
+ }
40
+ throw error;
41
+ }
42
+
43
+ return consoleImpl.init();
44
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @file none-console.js
3
+ * Implementation of the "none" console type
4
+ *
5
+ * @author Wes Garland, wes@distributive.network
6
+ * @date June 2025
7
+ */
8
+ 'use strict';
9
+
10
+ const fs = require('fs');
11
+ const os = require('os');
12
+ const { Console } = require('console');
13
+
14
+ exports.init = function noneConsole$$init()
15
+ {
16
+ const nullStream = fs.createWriteStream(os.devNull);
17
+ const console = new Console({ stdout: nullStream, stderr: nullStream });
18
+
19
+ console.setWorker = console.throb = console.close = () => 1;
20
+ return console;
21
+ }
22
+
23
+
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @file stdio-console.js
3
+ * Implementation of the "stdio" console type. This is the default in Node.js, so we
4
+ *
5
+ * @author Wes Garland, wes@distributive.network
6
+ * @date June 2023, June 2025
7
+ */
8
+ 'use strict';
9
+
10
+ const process = require('process');
11
+ const util = require('util');
12
+
13
+ const { Console } = require('console');
14
+ const { logLevels } = require('../consts');
15
+
16
+ const usingDebugger = require('module')._cache.niim instanceof require('module').Module;
17
+
18
+ /**
19
+ * Initialize the stdio console
20
+ *
21
+ * @param {object} options Any options affecting console behaviour. Not presently used.
22
+ */
23
+ exports.init = function stdioConsole$$init(options)
24
+ {
25
+ const { stderr, stdout } = process;
26
+ const console = new Console({ stderr, stdout });
27
+ var lastWasThrobber = false;
28
+ var throbIdx = 0;
29
+
30
+ console.setWorker = console.close = () => 1;
31
+
32
+ for (let logLevel in logLevels)
33
+ {
34
+ console[`__${logLevel}`] = console[logLevel];
35
+ console[logLevel] = function stdioConsoleLogWrapper() {
36
+ if (lastWasThrobber)
37
+ {
38
+ stdout.write('\n');
39
+ lastWasThrobber = false;
40
+ }
41
+ console[`__${logLevel}`].apply(this, arguments);
42
+ };
43
+ }
44
+
45
+ const throbChars = '/-\\|';
46
+ /**
47
+ * throb API: Writes message to stdout with a newline. Throb char is appended to message. If no message,
48
+ * advance the previous throb char.
49
+ */
50
+ console.throb = function throb(...args) {
51
+ if (args.length && lastWasThrobber)
52
+ stdout.write(' \n');
53
+
54
+ for (let i=0; i < args.length; i++)
55
+ {
56
+ if (i)
57
+ stdout.write(' ');
58
+ stdout.write(typeof args[i] === 'string' ? args[i] : util.inspect(args[i]));
59
+ }
60
+
61
+ if (stdout.isTTY && !usingDebugger)
62
+ {
63
+ throbIdx = (throbIdx + 1) % throbChars.length;
64
+ stdout.write(throbChars[throbIdx] + '\u0008');
65
+ lastWasThrobber = true;
66
+ }
67
+ }
68
+
69
+ return console;
70
+ }
@@ -1,18 +1,20 @@
1
1
  /**
2
- * @file worker-reporting.js
2
+ * @file worker-info.js
3
3
  * Check evaluator to determine if certain information including:
4
4
  * - if webgpu is enabled, and what capabilities it has.
5
5
  * - supported worktimes for the evaluator
6
- *
6
+ *
7
7
  * @author Ryan Saweczko, ryansaweczko@distributive.network
8
8
  *
9
9
  * @date Sept 2024
10
10
  */
11
11
  'use strict';
12
12
 
13
- const kvin = require('kvin');
14
13
  const evaluatorId = 'reportingCheck';
15
14
 
15
+ /**
16
+ * This function is serialized and executed inside the evaluator.
17
+ */
16
18
  async function eval$$getInfo()
17
19
  {
18
20
  const info = {};
@@ -47,7 +49,7 @@ async function eval$$getInfo()
47
49
  const adapterInfo = await adapter.requestAdapterInfo();
48
50
  for (let key of properties)
49
51
  webgpuInfo[key] = adapterInfo[key];
50
- info.webgpu = { enabled: true, info: webgpuInfo };
52
+ info.webgpu = { enabled: true, info: webgpuInfo };
51
53
  }
52
54
  }
53
55
  catch (err)
@@ -63,31 +65,38 @@ async function eval$$getInfo()
63
65
  /**
64
66
  * Connect to an evaluator instance and return back information on the evaluator
65
67
  * @param {object} evaluatorConfig - Object containing the hostname and port to connect to the evaluator instance on
66
- * @returns {Promise} which resolves with undefined detection failed (ie couldn't connect to evaluator), or the information object
68
+ * @returns {Promise} which resolves with
69
+ * - false when we can't connect to the evaluator, or
70
+ * - the evaluator's information object
71
+ * or which rejects with an error delivered by StandaloneWorker<error>
67
72
  */
68
73
  function getEvaluatorInformation(evaluatorConfig)
69
74
  {
70
75
  const StandaloneWorker = require('dcp-client/lib/standaloneWorker').workerFactory(evaluatorConfig);
71
- const { a$sleep } = require('dcp/utils');
72
-
73
76
  const evaluatorHandle = new StandaloneWorker({ name: 'DCP Sandbox #1', });
74
-
75
- var noResponse, resolve;
76
- const p$workerInfo = new Promise((res, rej) => { resolve = res; }).finally(() => {
77
+ var resolve, reject;
78
+ const p$workerInfo = new Promise((res, rej) => {
79
+ resolve = res;
80
+ reject = rej;
81
+ }).finally(() => {
77
82
  evaluatorHandle.terminate();
78
- noResponse.intr();
83
+ evaluatorHandle.removeAllListeners();
79
84
  });
85
+ evaluatorHandle.addEventListener('end', () => resolve(false));
86
+ evaluatorHandle.addEventListener('error', reject);
87
+ evaluatorHandle.ref();
80
88
 
81
- noResponse = a$sleep(2);
82
- noResponse.then(resolve); /* no answer */
83
- noResponse.finally(() => process.off('dcpBeforeExit', noResponse.intr));
84
- process.on('dcpBeforeExit', noResponse.intr);
85
-
86
- evaluatorHandle.onmessage = function onmessage(event)
89
+ evaluatorHandle.onmessage = function onmessage(__event)
87
90
  {
88
- const reply = kvin.unmarshal(event.data).value;
91
+ const event = StandaloneWorker.decodeMessageEvent(__event); /* should eventually be superflous /wg may 2025 */
92
+ const reply = event.data.value;
89
93
  if (reply.request === `evalResult::${evaluatorId}`)
90
- resolve(reply.data /* { enabled: false|true } */);
94
+ {
95
+ const workerInfo = reply.data;
96
+ if (typeof workerInfo !== 'object' || !workerInfo.worktimes || !workerInfo.webgpu)
97
+ throw new Error(`malformed response from evaluator`);
98
+ resolve(workerInfo);
99
+ }
91
100
  }
92
101
 
93
102
  const message = {
@@ -95,7 +104,7 @@ function getEvaluatorInformation(evaluatorConfig)
95
104
  data: '(' + eval$$getInfo.toString() + ')()',
96
105
  msgId: evaluatorId,
97
106
  }
98
- evaluatorHandle.postMessage(kvin.marshal(message));
107
+ evaluatorHandle.postMessage(StandaloneWorker.encodeMessage(message));
99
108
  return p$workerInfo;
100
109
  }
101
110
 
@@ -8,14 +8,17 @@
8
8
  */
9
9
  'use strict';
10
10
 
11
+ const assert = require('assert');
11
12
  const os = require('os');
13
+ var eventLogHnd;
14
+
12
15
  if (os.platform() !== 'win32')
13
16
  throw new Error(`Windows Event Log module is not supported on ${os.platform()}`);
14
17
 
15
- const { EventLog } = require('node-eventlog');
18
+ const { logLevels } = require('../consts');
19
+ const { EventLog } = require('node-eventlog');
20
+ const processName = require('path').basename(process.mainModule.filename);
16
21
 
17
- // Copy the original global console object's properties onto a backup
18
- const _console = Object.assign({}, console);
19
22
 
20
23
  /**
21
24
  * Initialize the eventlog worker logger
@@ -23,35 +26,30 @@ const _console = Object.assign({}, console);
23
26
  * @param {object} options Options for logger behaviour (passed
24
27
  * through to consoleLogger)
25
28
  */
26
- exports.init = function eventLog$$init(options)
29
+ exports.open = function eventLog$$open(options)
27
30
  {
28
- exports._processName = require('path').basename(process.mainModule.filename || process.argv0);
29
- const source = options.source || exports._processName || 'dcp-worker';
30
- exports._eventLog = new EventLog(source);
31
- require('../startWorkerLogger').inspectOptions.colors = false;
32
- exports.at = log;
31
+ const source = processName || 'dcp-worker';
32
+ eventLogHnd = new EventLog(source);
33
33
  }
34
34
 
35
35
  /**
36
- * Emit a message to the Windows event-log
36
+ * Emit a message to the Windows event-log
37
37
  * @param {string} level The node log level to log at
38
38
  * @param {[string]} items An array of strings to log as a single message
39
39
  */
40
- function log(level, ...items)
40
+ exports.at = function eventLog$$at(level, ...items)
41
41
  {
42
- {
43
- // Use the string log-level to look up the severity number:
44
- let severity = {
45
- error: 'error',
46
- warn: 'warn',
47
- log: 'info',
48
- info: 'info',
49
- debug: 'info',
50
- }[level];
51
-
52
- return exports._eventLog.log(items.join(' '), severity).catch(error => {
53
- if (error)
54
- _console.error('255: Unexpected error writing to event log:', error);
55
- });
56
- }
42
+ // Use the string log-level to look up the severity number:
43
+ let severity = {
44
+ [logLevels.error]: 'error',
45
+ [logLevels.warn]: 'warn',
46
+ [logLevels.notice]: 'info',
47
+ [logLevels.info]: 'info',
48
+ [logLevels.debug]: 'info',
49
+ }[level];
50
+
51
+ assert(severity);
52
+ return eventLogHnd.log(items.join(' '), severity || 'error').catch(exports.handleFatalError);
57
53
  }
54
+
55
+ exports.inspectOptions = { colors: false };