spooky.js
7.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
var spawn = require('child_process').spawn;
var util = require('util');
var _ = require('underscore');
var async = require('async');
var carrier = require('carrier');
var duplex = require('duplexer');
var EventEmitter = require('events').EventEmitter;
var Stream = require('stream');
var RequestStream = require('./spooky/request-stream');
var FilteredStream = require('./spooky/filtered-stream');
var tinyjsonrpc = require('tiny-jsonrpc');
var defaults = {
transport: {
http: {
host: 'localhost'
}
},
child: {
command: 'casperjs',
port: 8081,
script: __dirname + '/bootstrap.js',
spooky_lib: __dirname + '/../',
transport: 'stdio',
spawnOptions: {}
},
casper: {
verbose: true,
logLevel: 'debug'
}
};
function isJsonRpcRequest(s) {
try {
s = JSON.parse(s);
return s.jsonrpc === '2.0' && 'method' in s;
} catch (e) { /* intentionally empty */ }
return false;
}
function isJsonRpcResponse(s) {
try {
s = JSON.parse(s);
return s.jsonrpc === '2.0' &&
('result' in s || 'error' in s);
} catch (e) { /* intentionally empty */ }
return false;
}
function isFunctionTuple(a) {
return _.isArray(a) &&
a.length === 2 &&
_.isObject(a[0]) &&
_.isFunction(a[1]);
}
function serializeFunctions(x) {
if (_.isFunction(x)) {
x = x.toString();
} else if (isFunctionTuple(x)) {
x[1] = x[1].toString();
}
return x;
}
// serialize function values recursively
function serializeMethods(o) {
var v;
for (var k in o) {
v = o[k];
if (_.isObject(v) && !_.isArray(v) && !_.isFunction(v)) {
serializeMethods(v);
} else {
o[k] = serializeFunctions(v);
}
}
}
function Spooky(options, callback) {
EventEmitter.call(this);
this.options = options = _.defaults(_.clone(options || {}), defaults);
for (var k in defaults) {
if (defaults[k] && _.isObject(defaults[k]) && !_.isArray(defaults[k])) {
this.options[k] =
_.defaults(_.clone(options[k] || {}), defaults[k]);
}
}
options.transport = _.defaults(options.transport, defaults.transport);
this._q = async.queue(this._callWorker.bind(this), 1);
serializeMethods(options.casper);
if (options.child.transport === 'http') {
this._child = Spooky._instances[options.port] = this._spawnChild();
this._rpcClient = new tinyjsonrpc.StreamClient({
server: new RequestStream({
host: options.transport.http.host,
port: options.child.port
})
});
} else if (options.child.transport === 'stdio') {
this._child =
Spooky._instances['stdio' + Spooky._nextInstanceId++] =
this._spawnChild();
this._rpcClient = new tinyjsonrpc.StreamClient({
server: duplex(this._child.stdin,
new FilteredStream(this._child.stdout, isJsonRpcResponse))
});
// must terminate requests with a linefeed
this._rpcClient._send = function _send (request) {
if (this._server.full) {
this._server.buffer.push(request);
} else {
try {
request = JSON.stringify(request);
} catch (e) {
throw 'Could not serialize request to JSON';
}
this._server.full = !this._server.stream.write(request + '\n');
}
};
} else {
throw new Error('Unknown transport ' + options.child.transport);
}
// listen for JSON-RPC requests from the child
this._rpcServer = new tinyjsonrpc.StreamServer();
this._rpcServer.listen(duplex(
this._child.stdin,
new FilteredStream(this._child.stdout, isJsonRpcRequest)));
this._rpcServer.provide({
emit: function () {
this.emit.apply(this, arguments);
return true;
}.bind(this)
});
this.once('ready', function () {
this._call('create',
this._onCreate.bind(this, callback),
options.casper
);
}.bind(this));
}
util.inherits(Spooky, EventEmitter);
Spooky._instances = {};
Spooky._nextInstanceId = 0;
// clean up if spooky dies
process.on('exit', function () {
_.each(Spooky._instances, function (server) {
server.kill();
});
});
Spooky.prototype._spawnChild = function () {
var options = this.options.child;
var args = [ options.script ];
var child;
for (var k in options) {
if (k !== 'script') {
args.push('--' + k + '=' + options[k]);
}
}
if (Spooky._instances[options.port]) {
throw new Error('Already running a server on port ' + options.port);
}
child = this._child = spawn(options.command, args, options.spawnOptions);
var stdout = child.stdout;
stdout.setEncoding('utf8');
child.stdout = new Stream();
carrier.carry(stdout).on('line', function (line) {
this.stdout.emit('data', line);
}.bind(child));
// emit anything that isn't JSON-RPC traffic as a console event
(new FilteredStream(child.stdout, function (data) {
return !isJsonRpcResponse(data) && !isJsonRpcRequest(data);
})).on('data', function (data) {
this.emit('console', data.toString());
}.bind(this));
child.on('exit', function (code, signal) {
var e;
if (code) {
e = new Error('Child terminated with non-zero exit code ' + code);
e.details = {
code: code,
signal: signal
};
this.emit('error', e);
}
}.bind(this));
return child;
};
Spooky.prototype.destroy = function () {
this._child.kill();
delete Spooky._instances[this.options.child.port];
};
Spooky.create = function (options, callback) {
return new Spooky(options, callback);
};
Spooky.prototype._onLine = function (line) {
var response;
try {
response = JSON.parse(this._rpcServer.respond(line));
if (response.result === true) {
return;
}
} catch (e) { /* not JSON */ }
// either the line was not valid JSON or not a valid JSON-RPC request
this.emit('console', line);
};
Spooky.prototype._call = function (method, callback) {
var args = _.toArray(arguments);
var params = args.slice(2);
for (var i = 0; i < params.length; i++) {
params[i] = serializeFunctions(params[i]);
}
this._q.push({
method: method,
callback: callback,
params: params
});
};
// FIXME: does `callback` ever get used?
Spooky.prototype._callWorker = function (options, callback) {
var userCallback = options.callback;
options.callback = function (error, response) {
if (userCallback) {
userCallback.apply(this, arguments);
}
if (error) {
this.emit('error', error);
}
callback(error, response);
}.bind(this);
//call.apply(this, params);
this._rpcClient.request(options);
};
Spooky.prototype._onCreate = function (callback, error, response) {
var e;
if (!error) {
response.methods.forEach(function (method) {
this[method] =
this.constructor.prototype._call.bind(this, method, null);
}, this);
}
if (callback) {
callback(error, response);
} else if (error) {
e = new Error('Could not create Spooky instance');
e.details = error;
throw e;
}
};
module.exports = Spooky;