1 | boxed_eval = (s) ->
|
2 |
|
3 | eval "var retval = #{s}"
|
4 | retval
|
5 |
|
6 |
|
7 | box_error = (e) ->
|
8 | unless e instanceof Error
|
9 | throw new TypeError 'e is not an Error'
|
10 |
|
11 | {
|
12 | type: e.constructor.name
|
13 | parameters: {
|
14 | name: e.name
|
15 | message: e.message
|
16 | filename: e.filename
|
17 | lineNumber: e.lineNumber
|
18 | stack: e.stack
|
19 | }
|
20 | }
|
21 |
|
22 | builtin_process = process
|
23 |
|
24 | run = (process = builtin_process) ->
|
25 | cluster = require 'cluster'
|
26 |
|
27 | unless cluster.isWorker
|
28 | throw new Error 'needs to be cluster worker'
|
29 |
|
30 | count = 0
|
31 | inc = -> count++
|
32 | dec = ->
|
33 | count = Math.max(0, count - 1)
|
34 |
|
35 | if count is 0
|
36 | process.send {type: 'empty'}
|
37 |
|
38 | process.on 'message', (msg) ->
|
39 | work_fn = boxed_eval msg.work
|
40 |
|
41 | unless typeof work_fn is 'function'
|
42 | throw new TypeError 'work_fn not a function'
|
43 |
|
44 | inc()
|
45 |
|
46 | try
|
47 | work_fn msg.data..., (err, result) ->
|
48 | process.send
|
49 | type: 'result'
|
50 | contents:
|
51 | id: msg.id
|
52 | callback_params: [err, result]
|
53 |
|
54 | dec()
|
55 | catch e
|
56 | if e instanceof Error
|
57 | e = box_error e
|
58 |
|
59 | process.send
|
60 | type: 'exception'
|
61 | contents:
|
62 | id: msg.id
|
63 | is_error: true
|
64 | error: e
|
65 |
|
66 | else
|
67 | process.send
|
68 | type: 'exception'
|
69 | contents:
|
70 | id: msg.id
|
71 | is_error: false
|
72 | exception: e
|
73 |
|
74 | dec()
|
75 |
|
76 | if require.main is module
|
77 | run()
|
78 | else
|
79 | module.exports = run |
\ | No newline at end of file |