-
Notifications
You must be signed in to change notification settings - Fork 73
/
http.js
427 lines (380 loc) · 13.3 KB
/
http.js
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
/**
* A promise-based Q-JSGI server and client API.
* @module
*/
/*whatsupdoc*/
var HTTP = require("http"); // node
var HTTPS = require("https"); // node
var URL = require("url2"); // node
var Q = require("q");
var Reader = require("./reader");
/**
* @param {respond(request Request)} respond a JSGI responder function that
* receives a Request object as its argument. The JSGI responder promises to
* return an object of the form `{status, headers, body}`. The status and
* headers must be fully resolved, but the body may be a promise for an object
* with a `forEach(write(chunk String))` method, albeit an array of strings.
* The `forEach` method may promise to resolve when all chunks have been
* written.
* @returns a Node Server object.
*/
exports.Server = function (respond) {
var self = Object.create(exports.Server.prototype);
var server = HTTP.createServer(function (_request, _response) {
var request = exports.ServerRequest(_request);
var response = exports.ServerResponse(_response);
var closed = Q.defer();
_request.on("end", function (error, value) {
if (error) {
closed.reject(error);
} else {
closed.resolve(value);
}
});
Q.when(request, function (request) {
return Q.when(respond(request, response), function (response) {
if (!response)
return;
_response.writeHead(response.status, response.headers);
if (response.onclose || response.onClose)
Q.when(closed, response.onclose || response.onClose);
return Q.when(response.body, function (body) {
var length;
if (
Array.isArray(body) &&
(length = body.length) &&
body.every(function (chunk) {
return typeof chunk === "string"
})
) {
body.forEach(function (chunk, i) {
if (i < length - 1) {
_response.write(chunk, response.charset);
} else {
_response.end(chunk, response.charset);
}
});
} else if (body) {
var end;
var done = body.forEach(function (chunk) {
end = Q.when(end, function () {
return Q.when(chunk, function (chunk) {
_response.write(chunk, response.charset);
});
});
});
return Q.when(done, function () {
return Q.when(end, function () {
_response.end();
});
});
} else {
_response.end();
}
});
})
})
.done(); // should be .fail(self.emitter("error"))
});
var stopped = Q.defer();
server.on("close", function (err) {
if (err) {
stopped.reject(err);
} else {
stopped.resolve();
}
});
/***
* Stops the server.
* @returns {Promise * Undefined} a promise that will
* resolve when the server is stopped.
*/
self.stop = function () {
server.close();
listening = undefined;
return stopped.promise;
};
var listening = Q.defer();
server.on("listening", function (err) {
if (err) {
listening.reject(err);
} else {
listening.resolve(self);
}
});
/***
* Starts the server, listening on the given port
* @param {Number} port
* @returns {Promise * Undefined} a promise that will
* resolve when the server is ready to receive
* connections
*/
self.listen = function (/*...args*/) {
if (typeof server.port !== "undefined")
return Q.reject(new Error("A server cannot be restarted or " +
"started on a new port"));
server.listen.apply(server, arguments);
return listening.promise;
};
self.stopped = stopped.promise;
self.node = server;
self.nodeServer = server; // Deprecated
self.address = server.address.bind(server);
return self;
};
Object.defineProperties(exports.Server, {
port: {
get: function () {
return this.node.port;
}
},
host: {
get: function () {
return this.node.host;
}
}
});
/**
* A wrapper for a Node HTTP Request, as received by
* the Q HTTP Server, suitable for use by the Q HTTP Client.
*/
exports.ServerRequest = function (_request, ssl) {
var request = Object.create(_request, requestDescriptor);
/*** {Array} HTTP version. (JSGI) */
request.version = _request.httpVersion.split(".").map(Math.floor);
/*** {String} HTTP method, e.g., `"GET"` (JSGI) */
request.method = _request.method;
/*** {String} path, starting with `"/"` */
request.path = _request.url;
/*** {String} pathInfo, starting with `"/"`, the
* portion of the path that has not yet
* been routed (JSGI) */
request._pathInfo = null;
/*** {String} scriptName, the portion of the path that
* has already been routed (JSGI) */
request.scriptName = "";
/*** {String} (JSGI) */
request.scheme = "http";
var address = _request.connection.address();
/*** {String} hostname */
if (_request.headers.host) {
request.hostname = _request.headers.host.split(":")[0];
} else {
request.hostname = address.address;
}
/*** {String} host */
request.port = address.port;
var defaultPort = request.port === (ssl ? 443 : 80);
request.host = request.hostname + (defaultPort ? "" : ":" + request.port);
var socket = _request.socket;
/*** {String} */
request.remoteHost = socket.remoteAddress;
/*** {Number} */
request.remotePort = socket.remotePort;
/*** {String} url */
request.url = URL.format({
protocol: request.scheme,
host: _request.headers.host,
port: request.port === (ssl ? 443 : 80) ? null : request.port,
path: request.path
});
/*** A Q IO asynchronous text reader */
request.body = Reader(_request);
/*** {Object} HTTP headers (JSGI)*/
request.headers = _request.headers;
/*** The underlying Node request */
request.node = _request;
request.nodeRequest = _request; // Deprecated
/*** The underlying Node TCP connection */
request.nodeConnection = _request.connection;
return Q.when(request.body, function (body) {
request.body = body;
return request;
});
};
var requestDescriptor = {
pathInfo: {
get: function () {
// Postpone this until the server requests it because
// decodeURIComponent may throw an error if the path is not valid.
// If we throw while making a server request, it will crash the
// server and be uncatchable.
if (this._pathInfo === null) {
this._pathInfo = decodeURIComponent(URL.parse(this.url).pathname);
}
return this._pathInfo;
},
set: function (pathInfo) {
this._pathInfo = pathInfo;
}
}
};
exports.ServerResponse = function (_response, ssl) {
var response = Object.create(_response);
response.ssl = ssl;
response.node = _response;
response.nodeResponse = _response; // Deprecated
return response;
};
exports.normalizeRequest = function (request) {
if (typeof request === "string") {
request = {url: request};
}
request.method = request.method || "GET";
request.headers = request.headers || {};
if (request.url) {
var url = URL.parse(request.url);
request.ssl = url.protocol === "https:";
request.hostname = url.hostname;
request.host = url.host;
request.port = +url.port;
request.path = (url.pathname || "") + (url.search || "");
request.auth = url.auth || void 0;
}
request.host = request.host || request.headers.host;
request.port = request.port || (request.ssl ? 443 : 80);
if (request.host && !request.hostname) {
request.hostname = request.host.split(":")[0];
}
if (request.hostname && request.port && !request.host) {
var defaultPort = request.ssl ? 443 : 80;
request.host = request.hostname + (defaultPort ? "" : ":" + request.port);
}
request.headers.host = request.headers.host || request.host;
request.path = request.path || "/";
return request;
};
exports.normalizeResponse = function (response) {
if (response === void 0) {
return;
}
if (typeof response == "string") {
response = [response];
}
if (response.forEach) {
response = {
status: 200,
headers: {},
body: response
}
}
return response;
};
/**
* Issues an HTTP request.
*
* @param {Request {host, port, method, path, headers,
* body}} request (may be a promise)
* @returns {Promise * Response} promise for a response
*/
exports.request = function (request) {
return Q.when(request, function (request) {
request = exports.normalizeRequest(request);
var deferred = Q.defer();
var http = request.ssl ? HTTPS : HTTP;
var requestOptions = {
hostname: request.hostname,
port: request.port || (request.ssl ? 443 : 80),
localAddress: request.localAddress,
socketPath: request.socketPath,
method: request.method,
path: request.path,
headers: request.headers,
auth: request.auth // Generates the appropriate header
};
if (request.agent !== undefined) {
requestOptions.agent = request.agent;
}
if (request.cancelled) {
request.cancelled.then(function (value) {
throw new Error('`cancelled` promise on Q-IO HTTP request can only be rejected. Received resolution: ' + value);
}, function (error) {
_request.abort();
deferred.reject(error);
})
.done();
}
var _request = http.request(requestOptions, function (_response) {
deferred.resolve(exports.ClientResponse(_response, request.charset));
_response.on("error", function (error) {
// TODO find a better way to channel
// this into the response
console.warn(error && error.stack || error);
deferred.reject(error);
});
});
_request.on("error", function (error) {
deferred.reject(error);
});
if (request.timeout) {
_request.setTimeout(request.timeout, function() {
_request.abort();
});
}
Q.when(request.body, function (body) {
var end, done;
if (body) {
done = body.forEach(function (chunk) {
end = Q.when(end, function () {
return Q.when(chunk, function (chunk) {
_request.write(chunk, request.charset);
});
});
});
}
return Q.when(end, function () {
return Q.when(done, function () {
_request.end();
});
});
}).done();
return deferred.promise;
});
};
/**
* Issues a GET request to the given URL and returns
* a promise for a `String` containing the entirety
* of the response.
*
* @param {String} url
* @returns {Promise * String} or a rejection if the
* status code is not exactly 200. The reason for the
* rejection is the full response object.
*/
exports.read = function (request, qualifier) {
qualifier = qualifier || function (response) {
return response.status === 200;
};
return Q.when(exports.request(request), function (response) {
if (!qualifier(response)){
var error = new Error("HTTP request failed with code " + response.status);
error.response = response;
throw error;
}
return Q.post(response.body, 'read', []);
});
};
/**
* A wrapper for the Node HTTP Response as provided
* by the Q HTTP Client API, suitable for use by the
* Q HTTP Server API.
*/
exports.ClientResponse = function (_response, charset) {
var response = Object.create(exports.ClientResponse.prototype);
/*** {Number} HTTP status code */
response.status = _response.statusCode;
/*** HTTP version */
response.version = _response.httpVersion;
/*** {Object} HTTP headers */
response.headers = _response.headers;
/***
* A Q IO asynchronous text reader.
*/
response.node = _response;
response.nodeResponse = _response; // Deprecated
response.nodeConnection = _response.connection; // Deprecated
return Q.when(Reader(_response, charset), function (body) {
response.body = body;
return response;
});
};