child.js 1.9 KB

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