diff options
Diffstat (limited to 'src/nodejs')
-rw-r--r-- | src/nodejs/unit-http/binding.gyp | 2 | ||||
-rwxr-xr-x | src/nodejs/unit-http/http_server.js | 185 | ||||
-rw-r--r-- | src/nodejs/unit-http/package.json | 14 | ||||
-rwxr-xr-x | src/nodejs/unit-http/socket.js | 15 | ||||
-rw-r--r-- | src/nodejs/unit-http/unit.cpp | 104 | ||||
-rw-r--r-- | src/nodejs/unit-http/unit.h | 9 |
6 files changed, 226 insertions, 103 deletions
diff --git a/src/nodejs/unit-http/binding.gyp b/src/nodejs/unit-http/binding.gyp index 171c2eb7..ee09bfed 100644 --- a/src/nodejs/unit-http/binding.gyp +++ b/src/nodejs/unit-http/binding.gyp @@ -3,7 +3,7 @@ 'target_name': "unit-http", 'sources': ["unit.cpp", "addon.cpp"], 'include_dirs': [ - "<!(echo $UNIT_SRC_PATH)" + "<!(echo $UNIT_SRC_PATH)", "<!(echo $UNIT_BUILD_PATH)" ], 'libraries': [ "<!(echo $UNIT_LIB_STATIC_PATH)" diff --git a/src/nodejs/unit-http/http_server.js b/src/nodejs/unit-http/http_server.js index 57163c0b..057a1f26 100755 --- a/src/nodejs/unit-http/http_server.js +++ b/src/nodejs/unit-http/http_server.js @@ -47,44 +47,43 @@ ServerResponse.prototype.writeContinue = function writeContinue(cb) { ServerResponse.prototype.writeProcessing = function writeProcessing(cb) { }; -ServerResponse.prototype.setHeader = function setHeader(key, value) { - if (typeof key !== 'string') { - throw new TypeError('Key argument must be a string'); +ServerResponse.prototype.setHeader = function setHeader(name, value) { + if (typeof name !== 'string') { + throw new TypeError('Name argument must be a string'); } - let header_key_len = Buffer.byteLength(key, 'latin1'); - let header_len = 0 - let header_count = 0; + let value_len = 0 + let count = 0; if (Array.isArray(value)) { - header_count = value.length; + count = value.length; value.forEach(function(val) { - if (typeof val !== 'string' && typeof val !== 'number') { - throw new TypeError('Array entries must be string or number'); - } - - header_len += Buffer.byteLength(val + "", 'latin1'); + value_len += Buffer.byteLength(val + "", 'latin1'); }); } else { - if (typeof value !== 'string' && typeof value !== 'number') { - throw new TypeError('Value argument must be string, number, or array'); - } + count = 1; + value_len = Buffer.byteLength(value + "", 'latin1'); + } - header_count = 1; - header_len = Buffer.byteLength(value + "", 'latin1'); + let lc_name = name.toLowerCase(); + + if (lc_name in this.headers) { + this._removeHeader(lc_name); } - this.removeHeader(key); + let name_len = Buffer.byteLength(name, 'latin1'); - this.headers[key] = value; - this.headers_len += header_len + (header_key_len * header_count); - this.headers_count += header_count; + this.headers[lc_name] = [name, value]; + this.headers_len += value_len + (name_len * count); + this.headers_count += count; }; ServerResponse.prototype.getHeader = function getHeader(name) { - return this.headers[name]; + const entry = this.headers[name.toLowerCase()]; + + return entry && entry[1]; }; ServerResponse.prototype.getHeaderNames = function getHeaderNames() { @@ -92,34 +91,57 @@ ServerResponse.prototype.getHeaderNames = function getHeaderNames() { }; ServerResponse.prototype.getHeaders = function getHeaders() { - return this.headers; + const ret = Object.create(null); + + if (this.headers) { + const keys = Object.keys(this.headers); + + for (var i = 0; i < keys.length; i++) { + const key = keys[i]; + + ret[key] = this.headers[key][1]; + } + } + + return ret; }; ServerResponse.prototype.hasHeader = function hasHeader(name) { - return name in this.headers; + return name.toLowerCase() in this.headers; }; ServerResponse.prototype.removeHeader = function removeHeader(name) { - if (!(name in this.headers)) { - return; + if (typeof name !== 'string') { + throw new TypeError('Name argument must be a string'); } - let name_len = Buffer.byteLength(name + "", 'latin1'); + let lc_name = name.toLowerCase(); + + if (lc_name in this.headers) { + this._removeHeader(lc_name); + } +}; - if (Array.isArray(this.headers[name])) { - this.headers_count -= this.headers[name].length; - this.headers_len -= this.headers[name].length * name_len; +ServerResponse.prototype._removeHeader = function _removeHeader(lc_name) { + let entry = this.headers[lc_name]; + let name_len = Buffer.byteLength(entry[0] + "", 'latin1'); + let value = entry[1]; + + delete this.headers[lc_name]; + + if (Array.isArray(value)) { + this.headers_count -= value.length; + this.headers_len -= value.length * name_len; - this.headers[name].forEach(function(val) { + value.forEach(function(val) { this.headers_len -= Buffer.byteLength(val + "", 'latin1'); }); - } else { - this.headers_count--; - this.headers_len -= name_len + Buffer.byteLength(this.headers[name] + "", 'latin1'); + return; } - delete this.headers[name]; + this.headers_count--; + this.headers_len -= name_len + Buffer.byteLength(value + "", 'latin1'); }; ServerResponse.prototype.sendDate = function sendDate() { @@ -136,11 +158,6 @@ ServerResponse.prototype.setTimeout = function setTimeout(msecs, callback) { return this; }; -// for Express -ServerResponse.prototype._implicitHeader = function _implicitHeader() { - this.writeHead(this.statusCode); -}; - ServerResponse.prototype.writeHead = writeHead; ServerResponse.prototype.writeHeader = ServerResponse.prototype.writeHead; @@ -178,21 +195,16 @@ function writeHead(statusCode, reason, obj) { } } } - - unit_lib.unit_response_headers(this, statusCode, this.headers, this.headers_count, this.headers_len); - - this.headersSent = true; }; ServerResponse.prototype._writeBody = function(chunk, encoding, callback) { var contentLength = 0; if (!this.headersSent) { - this.writeHead(this.statusCode); - } + unit_lib.unit_response_headers(this, this.statusCode, this.headers, + this.headers_count, this.headers_len); - if (this.finished) { - return this; + this.headersSent = true; } if (typeof chunk === 'function') { @@ -220,20 +232,40 @@ ServerResponse.prototype._writeBody = function(chunk, encoding, callback) { } if (typeof callback === 'function') { - callback(this); + /* + * The callback must be called only when response.write() caller + * completes. process.nextTick() postpones the callback execution. + * + * process.nextTick() is not technically part of the event loop. + * Instead, the nextTickQueue will be processed after the current + * operation completes, regardless of the current phase of + * the event loop. All callbacks passed to process.nextTick() + * will be resolved before the event loop continues. + */ + process.nextTick(function () { + callback(this); + }.bind(this)); } }; ServerResponse.prototype.write = function write(chunk, encoding, callback) { + if (this.finished) { + throw new Error("Write after end"); + } + this._writeBody(chunk, encoding, callback); return true; }; ServerResponse.prototype.end = function end(chunk, encoding, callback) { - this._writeBody(chunk, encoding, callback); + if (!this.finished) { + this._writeBody(chunk, encoding, callback); - this.finished = true; + unit_lib.unit_response_end(this); + + this.finished = true; + } return this; }; @@ -285,6 +317,28 @@ ServerRequest.prototype.resume = function resume() { return []; }; +/* + * The "on" method is overridden to defer reading data until user code is + * ready, that is (ev === "data"). This can occur after req.emit("end") is + * executed, since the user code can be scheduled asynchronously by Promises + * and so on. Passing the data is postponed by process.nextTick() until + * the "on" method caller completes. + */ +ServerRequest.prototype.on = function on(ev, fn) { + Server.prototype.on.call(this, ev, fn); + + if (ev === "data") { + process.nextTick(function () { + if (this.server.buffer.length !== 0) { + this.emit("data", this.server.buffer); + } + + }.bind(this)); + } +}; + +ServerRequest.prototype.addListener = ServerRequest.prototype.on; + function Server(requestListener) { EventEmitter.call(this); @@ -317,28 +371,19 @@ Server.prototype.listen = function () { this.unit.listen(); }; -Server.prototype.run_events = function (server, req, res) { - /* Important!!! setImmediate starts the next iteration in Node.js loop. */ - setImmediate(function () { - server.emit("request", req, res); +Server.prototype.emit_events = function (server, req, res) { + req.server = server; + res.server = server; + req.res = res; + res.req = req; - Promise.resolve().then(() => { - let buf = server.unit._read(req.socket.req_pointer); + server.buffer = server.unit._read(req.socket.req_pointer); - if (buf.length != 0) { - req.emit("data", buf); - } - - req.emit("end"); - }); + server.emit("request", req, res); - Promise.resolve().then(() => { - req.emit("finish"); - - if (res.finished) { - unit_lib.unit_response_end(res); - } - }); + process.nextTick(() => { + req.emit("finish"); + req.emit("end"); }); }; diff --git a/src/nodejs/unit-http/package.json b/src/nodejs/unit-http/package.json index 3a15d573..13c91018 100644 --- a/src/nodejs/unit-http/package.json +++ b/src/nodejs/unit-http/package.json @@ -4,14 +4,15 @@ "description": "HTTP module for NGINX Unit", "main": "http.js", "files": [ + "unit.h", + "version.h", "addon.cpp", - "binding.gyp", - "http_server.js", + "unit.cpp", "http.js", + "http_server.js", "package.json", "socket.js", - "unit.cpp", - "unit.h", + "binding.gyp", "README.md" ], "scripts": { @@ -22,8 +23,5 @@ }, "author": "Alexander Borisov", "license": "Apache-2.0", - "gypfile": true, - "dependencies": { - "node-addon-api": "1.2.0" - } + "gypfile": true } diff --git a/src/nodejs/unit-http/socket.js b/src/nodejs/unit-http/socket.js index aef065bf..6e836949 100755 --- a/src/nodejs/unit-http/socket.js +++ b/src/nodejs/unit-http/socket.js @@ -18,10 +18,16 @@ function Socket(options) { throw new TypeError('Options must be object'); } - this.readable = (typeof options.readable === 'boolean' ? options.readable - : false); - this.writable = (typeof options.writable === 'boolean' ? options.writable - : false); + if ("fd" in options) { + throw new TypeError('Working with file descriptors not supported'); + } + + /* + * For HTTP TCP socket 'readable' and 'writable' are always true. + * These options are required by Express and Koa frameworks. + */ + this.readable = true; + this.writable = true; } util.inherits(Socket, EventEmitter); @@ -43,7 +49,6 @@ Socket.prototype.connect = function connect(options, connectListener) { this.once('connect', connectListener); this.connecting = true; - this.writable = true; return this; }; diff --git a/src/nodejs/unit-http/unit.cpp b/src/nodejs/unit-http/unit.cpp index be64a59b..60b0412a 100644 --- a/src/nodejs/unit-http/unit.cpp +++ b/src/nodejs/unit-http/unit.cpp @@ -276,12 +276,13 @@ Unit::_read(napi_env env, napi_callback_info info) void Unit::request_handler(nxt_unit_request_info_t *req) { - Unit *obj; - napi_value socket, request, response; - napi_value global, server_obj; - napi_value run_events, events_res; - napi_status status; - napi_value events_args[3]; + Unit *obj; + napi_value socket, request, response, global, server_obj, except; + napi_value emit_events, events_res, async_name, resource_object; + napi_status status; + napi_async_context async_context; + napi_callback_scope async_scope; + napi_value events_args[3]; obj = reinterpret_cast<Unit *>(req->unit->data); @@ -328,11 +329,11 @@ Unit::request_handler(nxt_unit_request_info_t *req) return; } - status = napi_get_named_property(obj->env_, server_obj, "run_events", - &run_events); + status = napi_get_named_property(obj->env_, server_obj, "emit_events", + &emit_events); if (status != napi_ok) { - napi_throw_error(obj->env_, NULL, "Failed to get" - " 'run_events' function"); + napi_throw_error(obj->env_, NULL, "Failed to get " + "'emit_events' function"); return; } @@ -340,15 +341,74 @@ Unit::request_handler(nxt_unit_request_info_t *req) events_args[1] = request; events_args[2] = response; - status = napi_call_function(obj->env_, server_obj, run_events, 3, - events_args, &events_res); + status = napi_create_string_utf8(obj->env_, "unit_request_handler", + sizeof("unit_request_handler") - 1, + &async_name); + if (status != napi_ok) { + napi_throw_error(obj->env_, NULL, "Failed to create utf-8 string"); + return; + } + + status = napi_async_init(obj->env_, NULL, async_name, &async_context); + if (status != napi_ok) { + napi_throw_error(obj->env_, NULL, "Failed to init async object"); + return; + } + + status = napi_create_object(obj->env_, &resource_object); + if (status != napi_ok) { + napi_throw_error(obj->env_, NULL, "Failed to create object for " + "callback scope"); + return; + } + + status = napi_open_callback_scope(obj->env_, resource_object, async_context, + &async_scope); + if (status != napi_ok) { + napi_throw_error(obj->env_, NULL, "Failed to open callback scope"); + return; + } + + status = napi_make_callback(obj->env_, async_context, server_obj, + emit_events, 3, events_args, &events_res); + if (status != napi_ok) { + if (status != napi_pending_exception) { + napi_throw_error(obj->env_, NULL, "Failed to make callback"); + return; + } + + status = napi_get_and_clear_last_exception(obj->env_, &except); + if (status != napi_ok) { + napi_throw_error(obj->env_, NULL, + "Failed to get and clear last exception"); + return; + } + + /* Logging a description of the error and call stack. */ + status = napi_fatal_exception(obj->env_, except); + if (status != napi_ok) { + napi_throw_error(obj->env_, NULL, "Failed to call " + "napi_fatal_exception() function"); + return; + } + } + + status = napi_close_callback_scope(obj->env_, async_scope); + if (status != napi_ok) { + napi_throw_error(obj->env_, NULL, "Failed to close callback scope"); + return; + } + + status = napi_async_destroy(obj->env_, async_context); if (status != napi_ok) { - napi_throw_error(obj->env_, NULL, "Failed to call" - " 'run_events' function"); + napi_throw_error(obj->env_, NULL, "Failed to destroy async object"); return; } - napi_close_handle_scope(obj->env_, scope); + status = napi_close_handle_scope(obj->env_, scope); + if (status != napi_ok) { + napi_throw_error(obj->env_, NULL, "Failed to close handle scope"); + } } @@ -694,7 +754,7 @@ Unit::response_send_headers(napi_env env, napi_callback_info info) uint32_t keys_count, i, j; uint16_t hash; napi_value this_arg, headers, keys, name, value, array_val; - napi_value req_num; + napi_value req_num, array_entry; napi_status status; napi_valuetype val_type; nxt_unit_field_t *f; @@ -771,7 +831,17 @@ Unit::response_send_headers(napi_env env, napi_callback_info info) goto failed; } - status = napi_get_property(env, headers, name, &value); + status = napi_get_property(env, headers, name, &array_entry); + if (status != napi_ok) { + goto failed; + } + + status = napi_get_element(env, array_entry, 0, &name); + if (status != napi_ok) { + goto failed; + } + + status = napi_get_element(env, array_entry, 1, &value); if (status != napi_ok) { goto failed; } diff --git a/src/nodejs/unit-http/unit.h b/src/nodejs/unit-http/unit.h index 5f541cc4..8baeb967 100644 --- a/src/nodejs/unit-http/unit.h +++ b/src/nodejs/unit-http/unit.h @@ -6,18 +6,23 @@ #ifndef _NXT_NODEJS_UNIT_H_INCLUDED_ #define _NXT_NODEJS_UNIT_H_INCLUDED_ - #include <node_api.h> - #ifdef __cplusplus extern "C" { #endif +#include "version.h" #include <nxt_unit.h> + +#if NXT_UNIT_VERNUM != NXT_NODE_VERNUM +#error "libunit version mismatch." +#endif + #include <nxt_unit_response.h> #include <nxt_unit_request.h> + #ifdef __cplusplus } /* extern "C" */ #endif |