项目原始demo,不改动
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
Это архивный репозиторий. Вы можете его клонировать или просматривать файлы, но не вносить изменения или открывать задачи/запросы на слияние.

4 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. 'use strict'
  2. const tape = require('tape')
  3. , child_process = require('child_process')
  4. , workerFarm = require('../')
  5. , childPath = require.resolve('./child')
  6. , fs = require('fs')
  7. , os = require('os')
  8. function uniq (ar) {
  9. let a = [], i, j
  10. o: for (i = 0; i < ar.length; ++i) {
  11. for (j = 0; j < a.length; ++j) if (a[j] == ar[i]) continue o
  12. a[a.length] = ar[i]
  13. }
  14. return a
  15. }
  16. // a child where module.exports = function ...
  17. tape('simple, exports=function test', function (t) {
  18. t.plan(4)
  19. let child = workerFarm(childPath)
  20. child(0, function (err, pid, rnd) {
  21. t.ok(pid > process.pid, 'pid makes sense')
  22. t.ok(pid < process.pid + 750, 'pid makes sense')
  23. t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense')
  24. })
  25. workerFarm.end(child, function () {
  26. t.ok(true, 'workerFarm ended')
  27. })
  28. })
  29. // a child where we have module.exports.fn = function ...
  30. tape('simple, exports.fn test', function (t) {
  31. t.plan(4)
  32. let child = workerFarm(childPath, [ 'run0' ])
  33. child.run0(function (err, pid, rnd) {
  34. t.ok(pid > process.pid, 'pid makes sense')
  35. t.ok(pid < process.pid + 750, 'pid makes sense')
  36. t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense')
  37. })
  38. workerFarm.end(child, function () {
  39. t.ok(true, 'workerFarm ended')
  40. })
  41. })
  42. // use the returned pids to check that we're using a single child process
  43. // when maxConcurrentWorkers = 1
  44. tape('single worker', function (t) {
  45. t.plan(2)
  46. let child = workerFarm({ maxConcurrentWorkers: 1 }, childPath)
  47. , pids = []
  48. , i = 10
  49. while (i--) {
  50. child(0, function (err, pid) {
  51. pids.push(pid)
  52. if (pids.length == 10) {
  53. t.equal(1, uniq(pids).length, 'only a single process (by pid)')
  54. } else if (pids.length > 10)
  55. t.fail('too many callbacks!')
  56. })
  57. }
  58. workerFarm.end(child, function () {
  59. t.ok(true, 'workerFarm ended')
  60. })
  61. })
  62. // use the returned pids to check that we're using two child processes
  63. // when maxConcurrentWorkers = 2
  64. tape('two workers', function (t) {
  65. t.plan(2)
  66. let child = workerFarm({ maxConcurrentWorkers: 2 }, childPath)
  67. , pids = []
  68. , i = 10
  69. while (i--) {
  70. child(0, function (err, pid) {
  71. pids.push(pid)
  72. if (pids.length == 10) {
  73. t.equal(2, uniq(pids).length, 'only two child processes (by pid)')
  74. } else if (pids.length > 10)
  75. t.fail('too many callbacks!')
  76. })
  77. }
  78. workerFarm.end(child, function () {
  79. t.ok(true, 'workerFarm ended')
  80. })
  81. })
  82. // use the returned pids to check that we're using a child process per
  83. // call when maxConcurrentWorkers = 10
  84. tape('many workers', function (t) {
  85. t.plan(2)
  86. let child = workerFarm({ maxConcurrentWorkers: 10 }, childPath)
  87. , pids = []
  88. , i = 10
  89. while (i--) {
  90. child(1, function (err, pid) {
  91. pids.push(pid)
  92. if (pids.length == 10) {
  93. t.equal(10, uniq(pids).length, 'pids are all the same (by pid)')
  94. } else if (pids.length > 10)
  95. t.fail('too many callbacks!')
  96. })
  97. }
  98. workerFarm.end(child, function () {
  99. t.ok(true, 'workerFarm ended')
  100. })
  101. })
  102. tape('auto start workers', function (t) {
  103. let child = workerFarm({ maxConcurrentWorkers: 3, autoStart: true }, childPath, ['uptime'])
  104. , pids = []
  105. , count = 5
  106. , i = count
  107. , delay = 250
  108. t.plan(count + 1)
  109. setTimeout(function() {
  110. while (i--)
  111. child.uptime(function (err, uptime) {
  112. t.ok(uptime > 10, 'child has been up before the request (' + uptime + 'ms)')
  113. })
  114. workerFarm.end(child, function () {
  115. t.ok(true, 'workerFarm ended')
  116. })
  117. }, delay)
  118. })
  119. // use the returned pids to check that we're using a child process per
  120. // call when we set maxCallsPerWorker = 1 even when we have maxConcurrentWorkers = 1
  121. tape('single call per worker', function (t) {
  122. t.plan(2)
  123. let child = workerFarm({
  124. maxConcurrentWorkers: 1
  125. , maxConcurrentCallsPerWorker: Infinity
  126. , maxCallsPerWorker: 1
  127. , autoStart: true
  128. }, childPath)
  129. , pids = []
  130. , count = 25
  131. , i = count
  132. while (i--) {
  133. child(0, function (err, pid) {
  134. pids.push(pid)
  135. if (pids.length == count) {
  136. t.equal(count, uniq(pids).length, 'one process for each call (by pid)')
  137. workerFarm.end(child, function () {
  138. t.ok(true, 'workerFarm ended')
  139. })
  140. } else if (pids.length > count)
  141. t.fail('too many callbacks!')
  142. })
  143. }
  144. })
  145. // use the returned pids to check that we're using a child process per
  146. // two-calls when we set maxCallsPerWorker = 2 even when we have maxConcurrentWorkers = 1
  147. tape('two calls per worker', function (t) {
  148. t.plan(2)
  149. let child = workerFarm({
  150. maxConcurrentWorkers: 1
  151. , maxConcurrentCallsPerWorker: Infinity
  152. , maxCallsPerWorker: 2
  153. , autoStart: true
  154. }, childPath)
  155. , pids = []
  156. , count = 20
  157. , i = count
  158. while (i--) {
  159. child(0, function (err, pid) {
  160. pids.push(pid)
  161. if (pids.length == count) {
  162. t.equal(count / 2, uniq(pids).length, 'one process for each call (by pid)')
  163. workerFarm.end(child, function () {
  164. t.ok(true, 'workerFarm ended')
  165. })
  166. } else if (pids.length > count)
  167. t.fail('too many callbacks!')
  168. })
  169. }
  170. })
  171. // use timing to confirm that one worker will process calls sequentially
  172. tape('many concurrent calls', function (t) {
  173. t.plan(2)
  174. let child = workerFarm({
  175. maxConcurrentWorkers: 1
  176. , maxConcurrentCallsPerWorker: Infinity
  177. , maxCallsPerWorker: Infinity
  178. , autoStart: true
  179. }, childPath)
  180. , defer = 200
  181. , count = 200
  182. , i = count
  183. , cbc = 0
  184. setTimeout(function () {
  185. let start = Date.now()
  186. while (i--) {
  187. child(defer, function () {
  188. if (++cbc == count) {
  189. let time = Date.now() - start
  190. // upper-limit not tied to `count` at all
  191. t.ok(time > defer && time < (defer * 2.5), 'processed tasks concurrently (' + time + 'ms)')
  192. workerFarm.end(child, function () {
  193. t.ok(true, 'workerFarm ended')
  194. })
  195. } else if (cbc > count)
  196. t.fail('too many callbacks!')
  197. })
  198. }
  199. }, 250)
  200. })
  201. // use timing to confirm that one child processes calls sequentially with
  202. // maxConcurrentCallsPerWorker = 1
  203. tape('single concurrent call', function (t) {
  204. t.plan(2)
  205. let child = workerFarm({
  206. maxConcurrentWorkers: 1
  207. , maxConcurrentCallsPerWorker: 1
  208. , maxCallsPerWorker: Infinity
  209. , autoStart: true
  210. }, childPath)
  211. , defer = 20
  212. , count = 100
  213. , i = count
  214. , cbc = 0
  215. setTimeout(function () {
  216. let start = Date.now()
  217. while (i--) {
  218. child(defer, function () {
  219. if (++cbc == count) {
  220. let time = Date.now() - start
  221. // upper-limit tied closely to `count`, 1.3 is generous but accounts for all the timers
  222. // coming back at the same time and the IPC overhead
  223. t.ok(time > (defer * count) && time < (defer * count * 1.3), 'processed tasks sequentially (' + time + ')')
  224. workerFarm.end(child, function () {
  225. t.ok(true, 'workerFarm ended')
  226. })
  227. } else if (cbc > count)
  228. t.fail('too many callbacks!')
  229. })
  230. }
  231. }, 250)
  232. })
  233. // use timing to confirm that one child processes *only* 5 calls concurrently
  234. tape('multiple concurrent calls', function (t) {
  235. t.plan(2)
  236. let callsPerWorker = 5
  237. , child = workerFarm({
  238. maxConcurrentWorkers: 1
  239. , maxConcurrentCallsPerWorker: callsPerWorker
  240. , maxCallsPerWorker: Infinity
  241. , autoStart: true
  242. }, childPath)
  243. , defer = 100
  244. , count = 100
  245. , i = count
  246. , cbc = 0
  247. setTimeout(function () {
  248. let start = Date.now()
  249. while (i--) {
  250. child(defer, function () {
  251. if (++cbc == count) {
  252. let time = Date.now() - start
  253. // (defer * (count / callsPerWorker + 1)) - if precise it'd be count/callsPerWorker
  254. // but accounting for IPC and other overhead, we need to give it a bit of extra time,
  255. // hence the +1
  256. t.ok(time > (defer * 1.5) && time < (defer * (count / callsPerWorker + 1)), 'processed tasks concurrently (' + time + 'ms)')
  257. workerFarm.end(child, function () {
  258. t.ok(true, 'workerFarm ended')
  259. })
  260. } else if (cbc > count)
  261. t.fail('too many callbacks!')
  262. })
  263. }
  264. }, 250)
  265. })
  266. // call a method that will die with a probability of 0.5 but expect that
  267. // we'll get results for each of our calls anyway
  268. tape('durability', function (t) {
  269. t.plan(3)
  270. let child = workerFarm({ maxConcurrentWorkers: 2 }, childPath, [ 'killable' ])
  271. , ids = []
  272. , pids = []
  273. , count = 20
  274. , i = count
  275. while (i--) {
  276. child.killable(i, function (err, id, pid) {
  277. ids.push(id)
  278. pids.push(pid)
  279. if (ids.length == count) {
  280. t.ok(uniq(pids).length > 2, 'processed by many (' + uniq(pids).length + ') workers, but got there in the end!')
  281. t.ok(uniq(ids).length == count, 'received a single result for each unique call')
  282. workerFarm.end(child, function () {
  283. t.ok(true, 'workerFarm ended')
  284. })
  285. } else if (ids.length > count)
  286. t.fail('too many callbacks!')
  287. })
  288. }
  289. })
  290. // a callback provided to .end() can and will be called (uses "simple, exports=function test" to create a child)
  291. tape('simple, end callback', function (t) {
  292. t.plan(4)
  293. let child = workerFarm(childPath)
  294. child(0, function (err, pid, rnd) {
  295. t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
  296. t.ok(pid < process.pid + 750, 'pid makes sense ' + pid + ' vs ' + process.pid)
  297. t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense')
  298. })
  299. workerFarm.end(child, function() {
  300. t.pass('an .end() callback was successfully called')
  301. })
  302. })
  303. tape('call timeout test', function (t) {
  304. t.plan(3 + 3 + 4 + 4 + 4 + 3 + 1)
  305. let child = workerFarm({ maxCallTime: 250, maxConcurrentWorkers: 1 }, childPath)
  306. // should come back ok
  307. child(50, function (err, pid, rnd) {
  308. t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
  309. t.ok(pid < process.pid + 750, 'pid makes sense ' + pid + ' vs ' + process.pid)
  310. t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd)
  311. })
  312. // should come back ok
  313. child(50, function (err, pid, rnd) {
  314. t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
  315. t.ok(pid < process.pid + 750, 'pid makes sense ' + pid + ' vs ' + process.pid)
  316. t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd)
  317. })
  318. // should die
  319. child(500, function (err, pid, rnd) {
  320. t.ok(err, 'got an error')
  321. t.equal(err.type, 'TimeoutError', 'correct error type')
  322. t.ok(pid === undefined, 'no pid')
  323. t.ok(rnd === undefined, 'no rnd')
  324. })
  325. // should die
  326. child(1000, function (err, pid, rnd) {
  327. t.ok(err, 'got an error')
  328. t.equal(err.type, 'TimeoutError', 'correct error type')
  329. t.ok(pid === undefined, 'no pid')
  330. t.ok(rnd === undefined, 'no rnd')
  331. })
  332. // should die even though it is only a 100ms task, it'll get caught up
  333. // in a dying worker
  334. setTimeout(function () {
  335. child(100, function (err, pid, rnd) {
  336. t.ok(err, 'got an error')
  337. t.equal(err.type, 'TimeoutError', 'correct error type')
  338. t.ok(pid === undefined, 'no pid')
  339. t.ok(rnd === undefined, 'no rnd')
  340. })
  341. }, 200)
  342. // should be ok, new worker
  343. setTimeout(function () {
  344. child(50, function (err, pid, rnd) {
  345. t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
  346. t.ok(pid < process.pid + 750, 'pid makes sense ' + pid + ' vs ' + process.pid)
  347. t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd)
  348. })
  349. workerFarm.end(child, function () {
  350. t.ok(true, 'workerFarm ended')
  351. })
  352. }, 400)
  353. })
  354. tape('test error passing', function (t) {
  355. t.plan(10)
  356. let child = workerFarm(childPath, [ 'err' ])
  357. child.err('Error', 'this is an Error', function (err) {
  358. t.ok(err instanceof Error, 'is an Error object')
  359. t.equal('Error', err.type, 'correct type')
  360. t.equal('this is an Error', err.message, 'correct message')
  361. })
  362. child.err('TypeError', 'this is a TypeError', function (err) {
  363. t.ok(err instanceof Error, 'is a TypeError object')
  364. t.equal('TypeError', err.type, 'correct type')
  365. t.equal('this is a TypeError', err.message, 'correct message')
  366. })
  367. child.err('Error', 'this is an Error with custom props', {foo: 'bar', 'baz': 1}, function (err) {
  368. t.ok(err instanceof Error, 'is an Error object')
  369. t.equal(err.foo, 'bar', 'passes data')
  370. t.equal(err.baz, 1, 'passes data')
  371. })
  372. workerFarm.end(child, function () {
  373. t.ok(true, 'workerFarm ended')
  374. })
  375. })
  376. tape('test maxConcurrentCalls', function (t) {
  377. t.plan(10)
  378. let child = workerFarm({ maxConcurrentCalls: 5 }, childPath)
  379. child(50, function (err) { t.notOk(err, 'no error') })
  380. child(50, function (err) { t.notOk(err, 'no error') })
  381. child(50, function (err) { t.notOk(err, 'no error') })
  382. child(50, function (err) { t.notOk(err, 'no error') })
  383. child(50, function (err) { t.notOk(err, 'no error') })
  384. child(50, function (err) {
  385. t.ok(err)
  386. t.equal(err.type, 'MaxConcurrentCallsError', 'correct error type')
  387. })
  388. child(50, function (err) {
  389. t.ok(err)
  390. t.equal(err.type, 'MaxConcurrentCallsError', 'correct error type')
  391. })
  392. workerFarm.end(child, function () {
  393. t.ok(true, 'workerFarm ended')
  394. })
  395. })
  396. // this test should not keep the process running! if the test process
  397. // doesn't die then the problem is here
  398. tape('test timeout kill', function (t) {
  399. t.plan(3)
  400. let child = workerFarm({ maxCallTime: 250, maxConcurrentWorkers: 1 }, childPath, [ 'block' ])
  401. child.block(function (err) {
  402. t.ok(err, 'got an error')
  403. t.equal(err.type, 'TimeoutError', 'correct error type')
  404. })
  405. workerFarm.end(child, function () {
  406. t.ok(true, 'workerFarm ended')
  407. })
  408. })
  409. tape('test max retries after process terminate', function (t) {
  410. t.plan(7)
  411. // temporary file is used to store the number of retries among terminating workers
  412. let filepath1 = '.retries1'
  413. let child1 = workerFarm({ maxConcurrentWorkers: 1, maxRetries: 5}, childPath, [ 'stubborn' ])
  414. child1.stubborn(filepath1, function (err, result) {
  415. t.notOk(err, 'no error')
  416. t.equal(result, 12, 'correct result')
  417. })
  418. workerFarm.end(child1, function () {
  419. fs.unlinkSync(filepath1)
  420. t.ok(true, 'workerFarm ended')
  421. })
  422. let filepath2 = '.retries2'
  423. let child2 = workerFarm({ maxConcurrentWorkers: 1, maxRetries: 3}, childPath, [ 'stubborn' ])
  424. child2.stubborn(filepath2, function (err, result) {
  425. t.ok(err, 'got an error')
  426. t.equal(err.type, 'ProcessTerminatedError', 'correct error type')
  427. t.equal(err.message, 'cancel after 3 retries!', 'correct message and number of retries')
  428. })
  429. workerFarm.end(child2, function () {
  430. fs.unlinkSync(filepath2)
  431. t.ok(true, 'workerFarm ended')
  432. })
  433. })
  434. tape('custom arguments can be passed to "fork"', function (t) {
  435. t.plan(3)
  436. // allocate a real, valid path, in any OS
  437. let cwd = fs.realpathSync(os.tmpdir())
  438. , workerOptions = {
  439. cwd : cwd
  440. , execArgv : ['--no-warnings']
  441. }
  442. , child = workerFarm({ maxConcurrentWorkers: 1, maxRetries: 5, workerOptions: workerOptions}, childPath, ['args'])
  443. child.args(function (err, result) {
  444. t.equal(result.execArgv[0], '--no-warnings', 'flags passed (overridden default)')
  445. t.equal(result.cwd, cwd, 'correct cwd folder')
  446. })
  447. workerFarm.end(child, function () {
  448. t.ok(true, 'workerFarm ended')
  449. })
  450. })
  451. tape('ensure --debug/--inspect not propagated to children', function (t) {
  452. t.plan(3)
  453. let script = __dirname + '/debug.js'
  454. , debugArg = process.version.replace(/^v(\d+)\..*$/, '$1') >= 8 ? '--inspect' : '--debug=8881'
  455. , child = child_process.spawn(process.execPath, [ debugArg, script ])
  456. , stdout = ''
  457. child.stdout.on('data', function (data) {
  458. stdout += data.toString()
  459. })
  460. child.on('close', function (code) {
  461. t.equal(code, 0, 'exited without error (' + code + ')')
  462. t.ok(stdout.indexOf('FINISHED') > -1, 'process finished')
  463. t.ok(stdout.indexOf('--debug') === -1, 'child does not receive debug flag')
  464. })
  465. })