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