UNPKG

1.86 kBJavaScriptView Raw
1'use strict'
2
3const fs = require('fs')
4const started = Date.now()
5
6
7module.exports = function (timeout, callback) {
8 callback = callback.bind(null, null, process.pid, Math.random(), timeout)
9 if (timeout)
10 return setTimeout(callback, timeout)
11 callback()
12}
13
14
15module.exports.args = function (callback) {
16 console.log(process.argv)
17 console.log(process.execArgv)
18 callback()
19}
20
21
22module.exports.run0 = function (callback) {
23 module.exports(0, callback)
24}
25
26
27module.exports.killable = function (id, callback) {
28 if (Math.random() < 0.5)
29 return process.exit(-1)
30 callback(null, id, process.pid)
31}
32
33
34module.exports.err = function (type, message, data, callback) {
35 if (typeof data == 'function') {
36 callback = data
37 data = null
38 } else {
39 let err = new Error(message)
40 Object.keys(data).forEach(function(key) {
41 err[key] = data[key]
42 })
43 callback(err)
44 return
45 }
46
47 if (type == 'TypeError')
48 return callback(new TypeError(message))
49 callback(new Error(message))
50}
51
52
53module.exports.block = function () {
54 while (true);
55}
56
57
58// use provided file path to save retries count among terminated workers
59module.exports.stubborn = function (path, callback) {
60 function isOutdated(path) {
61 return ((new Date).getTime() - fs.statSync(path).mtime.getTime()) > 2000
62 }
63
64 // file may not be properly deleted, check if modified no earler than two seconds ago
65 if (!fs.existsSync(path) || isOutdated(path)) {
66 fs.writeFileSync(path, '1')
67 process.exit(-1)
68 }
69
70 let retry = parseInt(fs.readFileSync(path, 'utf8'))
71 if (Number.isNaN(retry))
72 return callback(new Error('file contents is not a number'))
73
74 if (retry > 4) {
75 callback(null, 12)
76 } else {
77 fs.writeFileSync(path, String(retry + 1))
78 process.exit(-1)
79 }
80}
81
82
83module.exports.uptime = function (callback) {
84 callback(null, Date.now() - started)
85}