From 0b6a847694526f3fa57fdb8d012e89e3f0a2fbca Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 11 Sep 2015 16:34:31 +0800 Subject: [PATCH 001/131] Update for Node.js 4.0 --- example/serialize.js | 4 ++-- lib/client/Client.js | 14 ++++++------ lib/client/HttpClient.js | 4 ++-- lib/client/SocketClient.js | 4 ++-- lib/client/WebSocketClient.js | 4 ++-- lib/common/Future.js | 5 ++-- lib/common/HarmonyMaps.js | 10 ++++---- lib/common/isError.js | 41 +++++++++++++++++++++++++++++++++ lib/io/Writer.js | 12 +++++----- lib/server/Service.js | 43 ++++++++++++++++++----------------- package.json | 2 +- 11 files changed, 91 insertions(+), 52 deletions(-) create mode 100644 lib/common/isError.js diff --git a/example/serialize.js b/example/serialize.js index accce65..e9d6b3f 100644 --- a/example/serialize.js +++ b/example/serialize.js @@ -12,9 +12,9 @@ console.log(hprose.unserialize(hprose.serialize(12345678909876))); console.log(hprose.unserialize(hprose.serialize(Math.PI))); console.log(hprose.unserialize(hprose.serialize(new Date()))); console.log(hprose.serialize("Hello World!").toString()); -console.log(hprose.serialize("你好中国!").toString()); +console.log(hprose.serialize("你好中国!🇨🇳").toString()); console.log(hprose.unserialize(hprose.serialize("Hello World!"))); -console.log(hprose.unserialize(hprose.serialize("你好中国!"))); +console.log(hprose.unserialize(hprose.serialize("你好中国!🇨🇳"))); console.log(hprose.unserialize(hprose.serialize(new Buffer("你好"))).toString()); console.log(hprose.unserialize(new Buffer("l1234567890987654321234567890;"))); console.log(hprose.unserialize(hprose.serialize(NaN))); diff --git a/lib/client/Client.js b/lib/client/Client.js index 4902f7d..5bc6ed2 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Aug 18, 2015 * + * LastModified: Sep 11, 2015 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -209,7 +209,7 @@ function Client(uri, functions, settings) { if (typeof(methods) === s_string || methods.constructor === Object) { methods = [methods]; } - if (util.isArray(methods)) { + if (Array.isArray(methods)) { for (var i = 0; i < methods.length; i++) { var m = methods[i]; if (typeof(m) === s_string) { @@ -791,7 +791,7 @@ function Client(uri, functions, settings) { uri = false; } else if (uri && uri.constructor === Object || - util.isArray(uri)) { + Array.isArray(uri)) { functions = uri; uri = false; } @@ -811,7 +811,7 @@ function Client(uri, functions, settings) { (functions && functions.constructor === Object)) { functions = [functions]; } - if (util.isArray(functions)) { + if (Array.isArray(functions)) { setFunctions(stub, functions); } else { @@ -831,7 +831,7 @@ function Client(uri, functions, settings) { } if (argc === 1) args = []; if (argc === 2) { - if (!util.isArray(args)) { + if (!Array.isArray(args)) { var _args = []; if (typeof args !== s_function) { _args.push(noop); @@ -1142,7 +1142,7 @@ function Client(uri, functions, settings) { _index = 0; useService(uri, functions); } - else if (util.isArray(uri)) { + else if (Array.isArray(uri)) { _uris = uri; _index = Math.floor(Math.random() * _uris.length); useService(_uris[_index], functions); @@ -1185,7 +1185,7 @@ function create(uri, functions, settings) { if (typeof uri === 'string') { checkuri(uri); } - else if (util.isArray(uri)) { + else if (Array.isArray(uri)) { uri.forEach(function(uri) { checkuri(uri); }); throw new Error('Not support multiple protocol.'); } diff --git a/lib/client/HttpClient.js b/lib/client/HttpClient.js index 3a51591..454e69a 100644 --- a/lib/client/HttpClient.js +++ b/lib/client/HttpClient.js @@ -13,7 +13,7 @@ * * * Hprose Http Client for Node.js. * * * - * LastModified: Aug 5, 2015 * + * LastModified: Sep 11, 2015 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -229,7 +229,7 @@ function create(uri, functions, settings) { if (typeof uri === 'string') { checkuri(uri); } - else if (util.isArray(uri)) { + else if (Array.isArray(uri)) { uri.forEach(function(uri) { checkuri(uri); }); } else { diff --git a/lib/client/SocketClient.js b/lib/client/SocketClient.js index 0749418..4aac912 100644 --- a/lib/client/SocketClient.js +++ b/lib/client/SocketClient.js @@ -13,7 +13,7 @@ * * * Hprose Socket Client for Node.js. * * * - * LastModified: Aug 14, 2015 * + * LastModified: Sep 11, 2015 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -465,7 +465,7 @@ function create(uri, functions, settings) { if (typeof uri === 'string') { checkuri(uri); } - else if (util.isArray(uri)) { + else if (Array.isArray(uri)) { uri.forEach(function(uri) { checkuri(uri); }); } else { diff --git a/lib/client/WebSocketClient.js b/lib/client/WebSocketClient.js index b10a68d..07bb8b8 100644 --- a/lib/client/WebSocketClient.js +++ b/lib/client/WebSocketClient.js @@ -12,7 +12,7 @@ * * * Hprose WebSocket Client for HTML5. * * * - * LastModified: Aug 15, 2015 * + * LastModified: Sep 11, 2015 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -166,7 +166,7 @@ function create(uri, functions, settings) { if (typeof uri === 'string') { checkuri(uri); } - else if (util.isArray(uri)) { + else if (Array.isArray(uri)) { uri.forEach(function(uri) { checkuri(uri); }); } else { diff --git a/lib/common/Future.js b/lib/common/Future.js index c3fb4d2..430c33b 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Aug 2, 2015 * + * LastModified: Sep 11, 2015 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -21,7 +21,6 @@ /*jshint node:true, eqeqeq:true */ 'use strict'; -var util = require('util'); var TimeoutError = require('./TimeoutError'); var PENDING = 0; @@ -558,7 +557,7 @@ Object.defineProperties(Future.prototype, { } }, bind: { value: function(method) { var bindargs = slice(arguments); - if (util.isArray(method)) { + if (Array.isArray(method)) { for (var i = 0, n = method.length; i < n; ++i) { bindargs[0] = method[i]; this.bind.apply(this, bindargs); diff --git a/lib/common/HarmonyMaps.js b/lib/common/HarmonyMaps.js index 64c6ec6..a3f62b5 100644 --- a/lib/common/HarmonyMaps.js +++ b/lib/common/HarmonyMaps.js @@ -13,7 +13,7 @@ * * * Harmony Maps for Node.js. * * * - * LastModified: Aug 2, 2015 * + * LastModified: Sep 11, 2015 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -31,8 +31,6 @@ if (hasMap) { if (hasWeakMap && hasMap && hasForEach) return; -var util = require('util'); - var namespaces = Object.create(null); var count = 0; var reDefineValueOf = function (obj) { @@ -97,7 +95,7 @@ if (!hasWeakMap) { } } }); - if (arguments.length > 0 && util.isArray(arguments[0])) { + if (arguments.length > 0 && Array.isArray(arguments[0])) { var iterable = arguments[0]; for (var i = 0, len = iterable.length; i < len; i++) { m.set(iterable[i][0], iterable[i][1]); @@ -213,7 +211,7 @@ if (!hasMap) { } } }); - if (arguments.length > 0 && util.isArray(arguments[0])) { + if (arguments.length > 0 && Array.isArray(arguments[0])) { var iterable = arguments[0]; for (var i = 0, len = iterable.length; i < len; i++) { m.set(iterable[i][0], iterable[i][1]); @@ -284,7 +282,7 @@ if (!hasForEach) { } } }); - if (arguments.length > 0 && util.isArray(arguments[0])) { + if (arguments.length > 0 && Array.isArray(arguments[0])) { var iterable = arguments[0]; for (var i = 0, len = iterable.length; i < len; i++) { m.set(iterable[i][0], iterable[i][1]); diff --git a/lib/common/isError.js b/lib/common/isError.js new file mode 100644 index 0000000..caacea7 --- /dev/null +++ b/lib/common/isError.js @@ -0,0 +1,41 @@ +/**********************************************************\ +| | +| hprose | +| | +| Official WebSite: http://www.hprose.com/ | +| http://www.hprose.org/ | +| | +\**********************************************************/ + +/**********************************************************\ + * * + * hprose/common/isError.js * + * * + * isError for Node.js. * + * * + * LastModified: Sep 11, 2015 * + * Author: Ma Bingyao * + * * +\**********************************************************/ + +var objectToString = Object.prototype.toString; +var getPrototypeOf = Object.getPrototypeOf; +var ERROR_TYPE = '[object Error]'; + +function isError(err) { + if (err instanceof Error) { + return true; + } + if (typeof err !== 'object') { + return false; + } + while (err) { + if (objectToString.call(err) === ERROR_TYPE) { + return true; + } + err = getPrototypeOf(err); + } + return false; +} + +module.exports = isError; diff --git a/lib/io/Writer.js b/lib/io/Writer.js index 284e0e7..40f28bb 100644 --- a/lib/io/Writer.js +++ b/lib/io/Writer.js @@ -13,7 +13,7 @@ * * * Hprose Writer for Node.js. * * * - * LastModified: Aug 2, 2015 * + * LastModified: Sep 11, 2015 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -21,7 +21,6 @@ /*jshint node:true, eqeqeq:true, unused:false */ 'use strict'; -var util = require('util'); var Map = global.Map; var BytesIO = global.hprose.BytesIO; var Tags = global.hprose.Tags; @@ -125,12 +124,16 @@ function serialize(writer, value) { case Date: writer.writeDateWithRef(value); return; + case Array: + writer.writeListWithRef(value); + return; case Map: writer.writeMapWithRef(value); return; case ArrayBuffer: case Uint8Array: case BytesIO: + case Buffer: writer.writeBytesWithRef(value); return; case Int8Array: @@ -145,12 +148,9 @@ function serialize(writer, value) { writeDoubleListWithRef(writer, value); return; default: - if (util.isArray(value)) { + if (Array.isArray(value)) { writer.writeListWithRef(value); } - else if (util.isDate(value)) { - writer.writeDateWithRef(value); - } else if (Buffer.isBuffer(value)) { writer.writeBytesWithRef(value); } diff --git a/lib/server/Service.js b/lib/server/Service.js index 4b90e12..d76db2d 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Aug 9, 2015 * + * LastModified: Sep 11, 2015 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -23,6 +23,7 @@ var util = require('util'); var EventEmitter = require('events').EventEmitter; +var isError = require('../common/isError'); var TimeoutError = require('../common/TimeoutError'); var setImmediate = global.setImmediate; @@ -142,14 +143,14 @@ function Service() { } function sendError(error, context) { - if (!util.isError(error)) { + if (!isError(error)) { error = new Error(error); } try { self.emit('sendError', error, context); if (_onSendError !== null) { var e = _onSendError(error, context); - if (util.isError(e)) { + if (isError(e)) { error = e; } } @@ -175,10 +176,10 @@ function Service() { self.emit('beforeInvoke', name, args, context.byref, context); if (_onBeforeInvoke !== null) { var value = _onBeforeInvoke(name, args, context.byref, context); - if (util.isError(value)) throw value; + if (isError(value)) throw value; if (Future.isPromise(value)) { return value.then(function(e) { - if (util.isError(e)) throw e; + if (isError(e)) throw e; return invoke(name, args, context); }).catch(function(e) { return sendError(e, context); @@ -204,7 +205,7 @@ function Service() { return Future.promise(function(resolve, reject) { if (passContext) args.push(context); args.push(function(result) { - if (util.isError(result)) { + if (isError(result)) { reject(result); } else { @@ -224,7 +225,7 @@ function Service() { var result = _invokeHandler(name, args, context); if (Future.isPromise(result)) { return result.then(function(result) { - if (util.isError(result)) throw result; + if (isError(result)) throw result; return afterInvoke(name, args, context, result); }); } @@ -242,10 +243,10 @@ function Service() { self.emit('afterInvoke', name, args, context.byref, result, context); if (_onAfterInvoke !== null) { var value = _onAfterInvoke(name, args, context.byref, result, context); - if (util.isError(value)) throw value; + if (isError(value)) throw value; if (Future.isPromise(value)) { return value.then(function(e) { - if (util.isError(e)) throw e; + if (isError(e)) throw e; return doOutput(args, context, result); }); } @@ -705,7 +706,7 @@ function Service() { else if (typeof(args[0]) === 'string') { addFunction(global[args[0]], args[0]); } - else if (util.isArray(args[0])) { + else if (Array.isArray(args[0])) { addFunctions(args[0]); } else { @@ -722,8 +723,8 @@ function Service() { typeof(args[1]) === 'string') { addFunction(global[args[0]], args[1]); } - else if (util.isArray(args[0])) { - if (util.isArray(args[1])) { + else if (Array.isArray(args[0])) { + if (Array.isArray(args[1])) { addFunctions(args[0], args[1]); } else { @@ -750,8 +751,8 @@ function Service() { addFunction(global[args[0]], args[2]); } } - else if (util.isArray(args[0])) { - if (util.isArray(args[2]) && !args[1]) { + else if (Array.isArray(args[0])) { + if (Array.isArray(args[2]) && !args[1]) { addFunctions(args[0], args[2]); } else { @@ -777,7 +778,7 @@ function Service() { else if (typeof(args[0]) === 'string') { addAsyncFunction(global[args[0]], args[0]); } - else if (util.isArray(args[0])) { + else if (Array.isArray(args[0])) { addAsyncFunctions(args[0]); } else { @@ -794,8 +795,8 @@ function Service() { typeof(args[1]) === 'string') { addAsyncFunction(global[args[0]], args[1]); } - else if (util.isArray(args[0])) { - if (util.isArray(args[1])) { + else if (Array.isArray(args[0])) { + if (Array.isArray(args[1])) { addAsyncFunctions(args[0], args[1]); } else { @@ -822,8 +823,8 @@ function Service() { addAsyncFunction(global[args[0]], args[2]); } } - else if (util.isArray(args[0])) { - if (util.isArray(args[2]) && !args[1]) { + else if (Array.isArray(args[0])) { + if (Array.isArray(args[2]) && !args[1]) { addAsyncFunctions(args[0], args[2]); } else { @@ -895,7 +896,7 @@ function Service() { return request; } function publish(topic, options) { - if (util.isArray(topic)) { + if (Array.isArray(topic)) { topic.forEach(function(t) { publish(t, timeout); }); @@ -1038,7 +1039,7 @@ function Service() { var topics = getTopics(topic); for (id in topics) { _push(topic, id, result); } } - else if (util.isArray(id)) { + else if (Array.isArray(id)) { id.forEach(function(id) { _push(topic, id, result); }); } else { diff --git a/package.json b/package.json index 158b26f..d56dfcf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.5", + "version": "2.0.6", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From ed414f1cd4167525ee816991ff61b6b0f0936444 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 23 Sep 2015 20:18:25 +0800 Subject: [PATCH 002/131] Fixed a bug of hprose Service --- lib/server/Service.js | 10 ++++++++-- package.json | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index d76db2d..23b4a65 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Sep 11, 2015 * + * LastModified: Sep 23, 2015 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -186,7 +186,13 @@ function Service() { }); } } - return invoke(name, args, context); + var result = invoke(name, args, context); + if (Future.isPromise(result)) { + return result.catch(function(e) { + return sendError(e, context); + }); + } + return result; } catch (e) { return sendError(e, context); diff --git a/package.json b/package.json index d56dfcf..836700f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.6", + "version": "2.0.7", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 827ce9574ad43296c1243155745cd3e851654aae Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 2 Oct 2015 15:21:55 +0800 Subject: [PATCH 003/131] fixed package.son --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 836700f..07a74e6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.7", + "version": "2.0.8", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ @@ -52,7 +52,7 @@ "main": "lib/hprose.js", "optionalDependencies": { "ws": "*" }, "devDependencies": { - "promises-plus-tests": "*" + "promises-aplus-tests": "*" }, "scripts": { "aplus-tests": "promises-aplus-tests lib/hprose" From b4e9d3d940e452f52a62e4494fc3de9bfd8a2767 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 13 Dec 2015 20:32:08 +0800 Subject: [PATCH 004/131] Fixed batch invoke in service. --- lib/server/Service.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 23b4a65..1a06542 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Sep 23, 2015 * + * LastModified: Dec 13, 2015 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -295,20 +295,23 @@ function Service() { reader.reset(); var name = reader.readString(); var alias = name.toLowerCase(); + var cc = {}; + var key; + for (key in context) cc[key] = context[key]; var call = _calls[alias] || _calls['*']; if (call) { - for (var key in call) context[key] = call[key]; + for (key in call) cc[key] = call[key]; } var args = []; - context.byref = false; + cc.byref = false; tag = input.readByte(); if (tag === Tags.TagList) { - reader.useHarmonyMap = context.useHarmonyMap; + reader.useHarmonyMap = cc.useHarmonyMap; reader.reset(); args = reader.readListWithoutTag(); tag = input.readByte(); if (tag === Tags.TagTrue) { - context.byref = true; + cc.byref = true; tag = input.readByte(); } } @@ -318,10 +321,10 @@ function Service() { 'with following data: ' + input.toString()); } if (call) { - results.push(beforeInvoke(name, args, context)); + results.push(beforeInvoke(name, args, cc)); } else { - results.push(sendError(new Error('Can\'t find this function ' + name + '().'), context)); + results.push(sendError(new Error('Can\'t find this function ' + name + '().'), cc)); } } while (tag === Tags.TagCall); return Future.reduce(results, function(output, result) { From 3daa3261918d711f394c14af44b0447968e7d118 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 14 Dec 2015 20:49:16 +0800 Subject: [PATCH 005/131] Update to 2.0.9 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 07a74e6..e6083f9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.8", + "version": "2.0.9", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 3fbcae9ffcf86472e72cc091d27db8cd99039359 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 6 Feb 2016 13:45:29 +0800 Subject: [PATCH 006/131] Update LICENSE.md --- LICENSE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE.md b/LICENSE.md index 5a1390e..02bb1a1 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2008-2015 http://hprose.com +Copyright (c) 2008-2016 http://hprose.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in From b208acec7f27d02fba799003f0dc7376fdb67cd3 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 13 Feb 2016 13:42:32 +0800 Subject: [PATCH 007/131] Fixed the return value of readStringAsBytes Changed 0xDfff to 0xDFFF --- lib/io/BytesIO.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/io/BytesIO.js b/lib/io/BytesIO.js index 53e7b7b..46f7c37 100644 --- a/lib/io/BytesIO.js +++ b/lib/io/BytesIO.js @@ -13,7 +13,7 @@ * * * Hprose BytesIO for Node.js. * * * - * LastModified: Aug 21, 2015 * + * LastModified: Feb 13, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -52,7 +52,7 @@ function writeString(bytes, p, str) { bytes[p++] = 0xC0 | (codeUnit >> 6); bytes[p++] = 0x80 | (codeUnit & 0x3F); } - else if (codeUnit < 0xD800 || codeUnit > 0xDfff) { + else if (codeUnit < 0xD800 || codeUnit > 0xDFFF) { bytes[p++] = 0xE0 | (codeUnit >> 12); bytes[p++] = 0x80 | ((codeUnit >> 6) & 0x3F); bytes[p++] = 0x80 | (codeUnit & 0x3F); @@ -221,7 +221,7 @@ function readString(bytes, n) { function readStringAsBytes(bytes, n) { if (n === undefined) n = bytes.length; - if (n === 0) return _EMPTY_BYTES; + if (n === 0) return [_EMPTY_BYTES, 0]; var i = 0, off = 0; for (var len = bytes.length; i < n && off < len; i++) { var unit = bytes[off++]; From dd8e37ff5a32cdd1c1dda75282b70a3926b22193 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 13 Feb 2016 13:56:04 +0800 Subject: [PATCH 008/131] Improved some code --- lib/io/BytesIO.js | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/io/BytesIO.js b/lib/io/BytesIO.js index 46f7c37..56603d8 100644 --- a/lib/io/BytesIO.js +++ b/lib/io/BytesIO.js @@ -26,18 +26,18 @@ var _INIT_SIZE = 1024; var indexof = Function.prototype.call.bind(Array.prototype.indexOf); function writeInt32BE(bytes, p, i) { - bytes[p++] = i >>> 24 & 0xff; - bytes[p++] = i >>> 16 & 0xff; - bytes[p++] = i >>> 8 & 0xff; - bytes[p++] = i & 0xff; + bytes[p++] = i >>> 24 & 0xFF; + bytes[p++] = i >>> 16 & 0xFF; + bytes[p++] = i >>> 8 & 0xFF; + bytes[p++] = i & 0xFF; return p; } function writeInt32LE(bytes, p, i) { - bytes[p++] = i & 0xff; - bytes[p++] = i >>> 8 & 0xff; - bytes[p++] = i >>> 16 & 0xff; - bytes[p++] = i >>> 24 & 0xff; + bytes[p++] = i & 0xFF; + bytes[p++] = i >>> 8 & 0xFF; + bytes[p++] = i >>> 16 & 0xFF; + bytes[p++] = i >>> 24 & 0xFF; return p; } @@ -142,7 +142,7 @@ function readShortString(bytes, n) { function readLongString(bytes, n) { var buf = []; - var charCodes = new Uint16Array(0xffff); + var charCodes = new Uint16Array(0xFFFF); var i = 0, off = 0; for (var len = bytes.length; i < n && off < len; i++) { var unit = bytes[off++]; @@ -473,7 +473,7 @@ Object.defineProperties(BytesIO.prototype, { readUInt32BE: { value: function() { var value = this.readInt32BE(); if (value < 0) { - return (value & 0x7fffffff) + 0x80000000; + return (value & 0x7FFFFFFF) + 0x80000000; } return value; } }, @@ -493,7 +493,7 @@ Object.defineProperties(BytesIO.prototype, { readUInt32LE: { value: function() { var value = this.readInt32LE(); if (value < 0) { - return (value & 0x7fffffff) + 0x80000000; + return (value & 0x7FFFFFFF) + 0x80000000; } return value; } }, @@ -555,7 +555,7 @@ Object.defineProperties(BytesIO.prototype, { if (n < 100000) { return String.fromCharCode.apply(String, bytes); } - var remain = n & 0xffff; + var remain = n & 0xFFFF; var count = n >> 16; var a = new Array(remain ? count + 1 : count); for (var i = 0; i < count; ++i) { From a6a13ca237f8b1b6d866510d4e18a34d58b1b6f9 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 22 Feb 2016 00:11:23 +0800 Subject: [PATCH 009/131] Fixed writeUInt32BE & writeUInt32LE --- lib/client/SocketClient.js | 4 ++-- lib/io/BytesIO.js | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/client/SocketClient.js b/lib/client/SocketClient.js index 4aac912..ff3f6b3 100644 --- a/lib/client/SocketClient.js +++ b/lib/client/SocketClient.js @@ -13,7 +13,7 @@ * * * Hprose Socket Client for Node.js. * * * - * LastModified: Sep 11, 2015 * + * LastModified: Feb 22, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -328,7 +328,7 @@ HalfDuplexSocketTransporter.prototype = Object.create( var len = request.length; var buf = new Buffer(4 + len); - buf.writeUInt32BE(len, 0); + buf.writeInt32BE(len, 0); for (var i = 0; i < len; i++) { buf[i + 4] = request[i]; } diff --git a/lib/io/BytesIO.js b/lib/io/BytesIO.js index 56603d8..e03f5b3 100644 --- a/lib/io/BytesIO.js +++ b/lib/io/BytesIO.js @@ -13,7 +13,7 @@ * * * Hprose BytesIO for Node.js. * * * - * LastModified: Feb 13, 2016 * + * LastModified: Feb 22, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -385,9 +385,9 @@ Object.defineProperties(BytesIO.prototype, { throw new TypeError('value is out of bounds'); } }, writeUInt32BE: { value: function(i) { - if ((i === (i | 0)) && (i >= 0)) { + if (((i & 0x7FFFFFFF) + 0x80000000 === i) && (i >= 0)) { this._grow(4); - this._length = writeInt32BE(this._bytes, this._length, i); + this._length = writeInt32BE(this._bytes, this._length, i | 0); return; } throw new TypeError('value is out of bounds'); @@ -401,9 +401,9 @@ Object.defineProperties(BytesIO.prototype, { throw new TypeError('value is out of bounds'); } }, writeUInt32LE: { value: function(i) { - if ((i === (i | 0)) && (i >= 0)) { + if (((i & 0x7FFFFFFF) + 0x80000000 === i) && (i >= 0)) { this._grow(4); - this._length = writeInt32LE(this._bytes, this._length, i); + this._length = writeInt32LE(this._bytes, this._length, i | 0); return; } throw new TypeError('value is out of bounds'); From 02a7294e9028cca4be1164f5e1d0627d00cd28e7 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 25 Feb 2016 17:39:14 +0800 Subject: [PATCH 010/131] Update hprose for node.js --- lib/client/Client.js | 9 +- lib/client/HttpClient.js | 5 +- lib/client/SocketClient.js | 6 +- lib/client/WebSocketClient.js | 6 +- lib/common/Future.js | 1095 ++++++++++++++-------------- lib/common/HarmonyMaps.js | 493 ++++++------- lib/common/ResultMode.js | 5 +- lib/common/setImmediate.js | 65 +- lib/filter/JSONRPCClientFilter.js | 5 +- lib/filter/JSONRPCServiceFilter.js | 5 +- lib/hprose.js | 5 +- lib/io/BytesIO.js | 5 +- lib/io/ClassManager.js | 5 +- lib/io/Formatter.js | 5 +- lib/io/Reader.js | 6 +- lib/io/Tags.js | 5 +- lib/io/Writer.js | 5 +- lib/server/HttpServer.js | 5 +- lib/server/HttpService.js | 5 +- lib/server/Server.js | 5 +- lib/server/Service.js | 5 +- lib/server/SocketServer.js | 5 +- lib/server/SocketService.js | 5 +- lib/server/WebSocketServer.js | 5 +- lib/server/WebSocketService.js | 7 +- 25 files changed, 894 insertions(+), 878 deletions(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index 5bc6ed2..d6b4fa0 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,13 +13,13 @@ * * * HproseClient for Node.js. * * * - * LastModified: Sep 11, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ -/*global Proxy */ +/*global global, Proxy */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); @@ -137,8 +137,7 @@ function Client(uri, functions, settings) { } if (context.idempotent) { if (--context.retry >= 0) { - var interval = (10 - context.retry) * 500; - if (context.retry > 10) interval = 500; + var interval = (context.retry >= 10) ? 500 : (10 - context.retry) * 500; global.setTimeout(function() { sendAndReceive(data, context, onsuccess, onerror); }, interval); diff --git a/lib/client/HttpClient.js b/lib/client/HttpClient.js index 454e69a..eee802a 100644 --- a/lib/client/HttpClient.js +++ b/lib/client/HttpClient.js @@ -13,12 +13,13 @@ * * * Hprose Http Client for Node.js. * * * - * LastModified: Sep 11, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); diff --git a/lib/client/SocketClient.js b/lib/client/SocketClient.js index ff3f6b3..e6e4d8a 100644 --- a/lib/client/SocketClient.js +++ b/lib/client/SocketClient.js @@ -13,19 +13,19 @@ * * * Hprose Socket Client for Node.js. * * * - * LastModified: Feb 22, 2016 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); var net = require('net'); var tls = require('tls'); var parse = require('url').parse; -var EventEmitter = require('events').EventEmitter; var TimeoutError = require('../common/TimeoutError'); var Client = global.hprose.Client; diff --git a/lib/client/WebSocketClient.js b/lib/client/WebSocketClient.js index 07bb8b8..8fde22d 100644 --- a/lib/client/WebSocketClient.js +++ b/lib/client/WebSocketClient.js @@ -12,12 +12,13 @@ * * * Hprose WebSocket Client for HTML5. * * * - * LastModified: Sep 11, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); @@ -39,7 +40,6 @@ function WebSocketClient(uri, functions, settings) { var _id = 0; var _count = 0; - var _reqcount = 0; var _futures = []; var _requests = []; var _ready = null; diff --git a/lib/common/Future.js b/lib/common/Future.js index 430c33b..b5e0fc8 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,640 +13,643 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Sep 11, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ -'use strict'; - -var TimeoutError = require('./TimeoutError'); +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ +(function() { + 'use strict'; + + var TimeoutError = require('./TimeoutError'); + + var PENDING = 0; + var FULFILLED = 1; + var REJECTED = 2; + + var hasPromise = 'Promise' in global; + var setImmediate = global.setImmediate; + var setTimeout = global.setTimeout; + var clearTimeout = global.clearTimeout; + var foreach = Function.prototype.call.bind(Array.prototype.forEach); + var slice = Function.prototype.call.bind(Array.prototype.slice); + + function Future(computation) { + Object.defineProperties(this, { + _subscribers: { value: [] }, + resolve: { value: this.resolve.bind(this) }, + reject: { value: this.reject.bind(this) }, + }); + var self = this; + if (typeof computation === 'function') { + setImmediate(function() { + try { + self.resolve(computation()); + } + catch(e) { + self.reject(e); + } + }); + } + } -var PENDING = 0; -var FULFILLED = 1; -var REJECTED = 2; + function isFuture(obj) { + return obj instanceof Future; + } -var hasPromise = 'Promise' in global; -var setImmediate = global.setImmediate; -var setTimeout = global.setTimeout; -var clearTimeout = global.clearTimeout; -var foreach = Function.prototype.call.bind(Array.prototype.forEach); -var slice = Function.prototype.call.bind(Array.prototype.slice); + function isPromise(obj) { + return isFuture(obj) || (hasPromise && (obj instanceof global.Promise) && (typeof (obj.then === 'function'))); + } -function Future(computation) { - Object.defineProperties(this, { - _subscribers: { value: [] }, - resolve: { value: this.resolve.bind(this) }, - reject: { value: this.reject.bind(this) }, - }); - var self = this; - if (typeof computation === 'function') { - setImmediate(function() { + function delayed(duration, value) { + var computation = (typeof value === 'function') ? + value : + function() { return value; }; + var future = new Future(); + setTimeout(function() { try { - self.resolve(computation()); + future.resolve(computation()); } catch(e) { - self.reject(e); + future.reject(e); } - }); + }, duration); + return future; } -} - -function isFuture(obj) { - return obj instanceof Future; -} - -function isPromise(obj) { - return isFuture(obj) || (hasPromise && (obj instanceof global.Promise) && (typeof (obj.then === 'function'))); -} - -function delayed(duration, value) { - var computation = (typeof value === 'function') ? - value : - function() { return value; }; - var future = new Future(); - setTimeout(function() { + + function error(e) { + var future = new Future(); + future.reject(e); + return future; + } + + function value(v) { + var future = new Future(); + future.resolve(v); + return future; + } + + function sync(computation) { try { - future.resolve(computation()); + var result = computation(); + return value(result); } catch(e) { - future.reject(e); + return error(e); } - }, duration); - return future; -} - -function error(e) { - var future = new Future(); - future.reject(e); - return future; -} - -function value(v) { - var future = new Future(); - future.resolve(v); - return future; -} - -function sync(computation) { - try { - var result = computation(); - return value(result); - } - catch(e) { - return error(e); } -} - -function promise(executor) { - var future = new Future(); - executor(future.resolve, future.reject); - return future; -} - -function arraysize(array) { - var size = 0; - foreach(array, function() { ++size; }); - return size; -} - -function all(array) { - array = isPromise(array) ? array : value(array); - return array.then(function(array) { - var n = array.length; - var count = arraysize(array); - var result = new Array(n); - if (count === 0) return value(result); + + function promise(executor) { var future = new Future(); - foreach(array, function(element, index) { - var f = (isPromise(element) ? element : value(element)); - f.then(function(value) { - result[index] = value; - if (--count === 0) { - future.resolve(result); - } - }, - future.reject); - }); + executor(future.resolve, future.reject); return future; - }); -} + } -function join() { - return all(arguments); -} + function arraysize(array) { + var size = 0; + foreach(array, function() { ++size; }); + return size; + } -function race(array) { - array = isPromise(array) ? array : value(array); - return array.then(function(array) { - var future = new Future(); - foreach(array, function(element) { - var f = (isPromise(element) ? element : value(element)); - f.then(future.resolve, future.reject); + function all(array) { + array = isPromise(array) ? array : value(array); + return array.then(function(array) { + var n = array.length; + var count = arraysize(array); + var result = new Array(n); + if (count === 0) return value(result); + var future = new Future(); + foreach(array, function(element, index) { + var f = (isPromise(element) ? element : value(element)); + f.then(function(value) { + result[index] = value; + if (--count === 0) { + future.resolve(result); + } + }, + future.reject); + }); + return future; }); - return future; - }); -} - -function any(array) { - array = isPromise(array) ? array : value(array); - return array.then(function(array) { - var n = array.length; - var count = arraysize(array); - if (count === 0) { - throw new RangeError('any(): array must not be empty'); - } - var reasons = new Array(n); - var future = new Future(); - foreach(array, function(element, index) { - var f = (isPromise(element) ? element : value(element)); - f.then(future.resolve, function(e) { - reasons[index] = e; - if (--count === 0) { - future.reject(reasons); - } + } + + function join() { + return all(arguments); + } + + function race(array) { + array = isPromise(array) ? array : value(array); + return array.then(function(array) { + var future = new Future(); + foreach(array, function(element) { + var f = (isPromise(element) ? element : value(element)); + f.then(future.resolve, future.reject); }); + return future; }); - return future; - }); -} - -function settle(array) { - array = isPromise(array) ? array : value(array); - return array.then(function(array) { - var n = array.length; - var count = arraysize(array); - var result = new Array(n); - if (count === 0) return value(result); - var future = new Future(); - foreach(array, function(element, index) { - var f = (isPromise(element) ? element : value(element)); - f.whenComplete(function() { - result[index] = f.inspect(); - if (--count === 0) { - future.resolve(result); - } + } + + function any(array) { + array = isPromise(array) ? array : value(array); + return array.then(function(array) { + var n = array.length; + var count = arraysize(array); + if (count === 0) { + throw new RangeError('any(): array must not be empty'); + } + var reasons = new Array(n); + var future = new Future(); + foreach(array, function(element, index) { + var f = (isPromise(element) ? element : value(element)); + f.then(future.resolve, function(e) { + reasons[index] = e; + if (--count === 0) { + future.reject(reasons); + } + }); }); + return future; }); - return future; - }); -} + } -function attempt(handler/*, arg1, arg2, ... */) { - var args = slice(arguments, 1); - return all(args).then(function(args) { - return handler.apply(undefined, args); - }); -} + function settle(array) { + array = isPromise(array) ? array : value(array); + return array.then(function(array) { + var n = array.length; + var count = arraysize(array); + var result = new Array(n); + if (count === 0) return value(result); + var future = new Future(); + foreach(array, function(element, index) { + var f = (isPromise(element) ? element : value(element)); + f.whenComplete(function() { + result[index] = f.inspect(); + if (--count === 0) { + future.resolve(result); + } + }); + }); + return future; + }); + } -function run(handler, thisArg/*, arg1, arg2, ... */) { - var args = slice(arguments, 2); - return all(args).then(function(args) { - return handler.apply(thisArg, args); - }); -} + function attempt(handler/*, arg1, arg2, ... */) { + var args = slice(arguments, 1); + return all(args).then(function(args) { + return handler.apply(undefined, args); + }); + } -function wrap(handler, thisArg) { - return function() { - return all(arguments).then(function(args) { + function run(handler, thisArg/*, arg1, arg2, ... */) { + var args = slice(arguments, 2); + return all(args).then(function(args) { return handler.apply(thisArg, args); }); - }; -} + } -function forEach(array, callback, thisArg) { - return all(array).then(function(array) { - return array.forEach(callback, thisArg); - }); -} + function wrap(handler, thisArg) { + return function() { + return all(arguments).then(function(args) { + return handler.apply(thisArg, args); + }); + }; + } -function every(array, callback, thisArg) { - return all(array).then(function(array) { - return array.every(callback, thisArg); - }); -} + function forEach(array, callback, thisArg) { + return all(array).then(function(array) { + return array.forEach(callback, thisArg); + }); + } -function some(array, callback, thisArg) { - return all(array).then(function(array) { - return array.some(callback, thisArg); - }); -} + function every(array, callback, thisArg) { + return all(array).then(function(array) { + return array.every(callback, thisArg); + }); + } -function filter(array, callback, thisArg) { - return all(array).then(function(array) { - return array.filter(callback, thisArg); - }); -} + function some(array, callback, thisArg) { + return all(array).then(function(array) { + return array.some(callback, thisArg); + }); + } -function map(array, callback, thisArg) { - return all(array).then(function(array) { - return array.map(callback, thisArg); - }); -} + function filter(array, callback, thisArg) { + return all(array).then(function(array) { + return array.filter(callback, thisArg); + }); + } -function reduce(array, callback, initialValue) { - if (arguments.length > 2) { + function map(array, callback, thisArg) { return all(array).then(function(array) { - if (!isPromise(initialValue)) { - initialValue = value(initialValue); - } - return initialValue.then(function(value) { - return array.reduce(callback, value); - }); + return array.map(callback, thisArg); }); } - return all(array).then(function(array) { - return array.reduce(callback); - }); -} -function reduceRight(array, callback, initialValue) { - if (arguments.length > 2) { + function reduce(array, callback, initialValue) { + if (arguments.length > 2) { + return all(array).then(function(array) { + if (!isPromise(initialValue)) { + initialValue = value(initialValue); + } + return initialValue.then(function(value) { + return array.reduce(callback, value); + }); + }); + } return all(array).then(function(array) { - if (!isPromise(initialValue)) { - initialValue = value(initialValue); - } - return initialValue.then(function(value) { - return array.reduceRight(callback, value); + return array.reduce(callback); + }); + } + + function reduceRight(array, callback, initialValue) { + if (arguments.length > 2) { + return all(array).then(function(array) { + if (!isPromise(initialValue)) { + initialValue = value(initialValue); + } + return initialValue.then(function(value) { + return array.reduceRight(callback, value); + }); }); + } + return all(array).then(function(array) { + return array.reduceRight(callback); }); } - return all(array).then(function(array) { - return array.reduceRight(callback); + + Object.defineProperties(Future, { + // port from Dart + delayed: { value: delayed }, + error: { value: error }, + sync: { value: sync }, + value: { value: value }, + // Promise compatible + all: { value: all }, + race: { value: race }, + resolve: { value: value }, + reject: { value: error }, + // extended methods + promise: { value: promise }, + isFuture: { value: isFuture }, + isPromise: { value: isPromise }, + join: { value: join }, + any: { value: any }, + settle: { value: settle }, + attempt: { value: attempt }, + run: { value: run }, + wrap: { value: wrap }, + // for array + forEach: { value: forEach }, + every: { value: every }, + some: { value: some }, + filter: { value: filter }, + map: { value: map }, + reduce: { value: reduce }, + reduceRight: { value: reduceRight } }); -} - -Object.defineProperties(Future, { - // port from Dart - delayed: { value: delayed }, - error: { value: error }, - sync: { value: sync }, - value: { value: value }, - // Promise compatible - all: { value: all }, - race: { value: race }, - resolve: { value: value }, - reject: { value: error }, - // extended methods - promise: { value: promise }, - isFuture: { value: isFuture }, - isPromise: { value: isPromise }, - join: { value: join }, - any: { value: any }, - settle: { value: settle }, - attempt: { value: attempt }, - run: { value: run }, - wrap: { value: wrap }, - // for array - forEach: { value: forEach }, - every: { value: every }, - some: { value: some }, - filter: { value: filter }, - map: { value: map }, - reduce: { value: reduce }, - reduceRight: { value: reduceRight } -}); - -function _call(callback, next, x) { - setImmediate(function() { - try { - var r = callback(x); - next.resolve(r); + + function _call(callback, next, x) { + setImmediate(function() { + try { + var r = callback(x); + next.resolve(r); + } + catch(e) { + next.reject(e); + } + }); + } + + function _reject(onreject, next, e) { + if (onreject) { + _call(onreject, next, e); } - catch(e) { + else { next.reject(e); } - }); -} - -function _reject(onreject, next, e) { - if (onreject) { - _call(onreject, next, e); - } - else { - next.reject(e); } -} -function _resolve(onfulfill, onreject, self, next, x) { - function resolvePromise(y) { - _resolve(onfulfill, onreject, self, next, y); - } - function rejectPromise(r) { - _reject(onreject, next, r); - } - if (isPromise(x)) { - if (x === self) { - rejectPromise(new TypeError('Self resolution')); - return; + function _resolve(onfulfill, onreject, self, next, x) { + function resolvePromise(y) { + _resolve(onfulfill, onreject, self, next, y); } - x.then(resolvePromise, rejectPromise); - return; - } - if ((x !== null) && - (typeof x === 'object') || - (typeof x === 'function')) { - var then; - try { - then = x.then; + function rejectPromise(r) { + _reject(onreject, next, r); } - catch (e) { - rejectPromise(e); + if (isPromise(x)) { + if (x === self) { + rejectPromise(new TypeError('Self resolution')); + return; + } + x.then(resolvePromise, rejectPromise); return; } - if (typeof then === 'function') { - var notrun = true; + if ((x !== null) && + (typeof x === 'object') || + (typeof x === 'function')) { + var then; try { - then.call(x, function(y) { - if (notrun) { - notrun = false; - resolvePromise(y); - } - }, function(r) { + then = x.then; + } + catch (e) { + rejectPromise(e); + return; + } + if (typeof then === 'function') { + var notrun = true; + try { + then.call(x, function(y) { + if (notrun) { + notrun = false; + resolvePromise(y); + } + }, function(r) { + if (notrun) { + notrun = false; + rejectPromise(r); + } + }); + return; + } + catch (e) { if (notrun) { notrun = false; - rejectPromise(r); + rejectPromise(e); } - }); - return; - } - catch (e) { - if (notrun) { - notrun = false; - rejectPromise(e); } + return; } - return; } - } - if (onfulfill) { - _call(onfulfill, next, x); - } - else { - next.resolve(x); - } -} - -Object.defineProperties(Future.prototype, { - _value: { writable: true }, - _reason: { writable: true }, - _state: { value: PENDING, writable: true }, - resolve: { value: function(value) { - if (this._state === PENDING) { - this._state = FULFILLED; - this._value = value; - var subscribers = this._subscribers; - while (subscribers.length > 0) { - var subscriber = subscribers.shift(); - _resolve(subscriber.onfulfill, - subscriber.onreject, - this, - subscriber.next, - value); - } + if (onfulfill) { + _call(onfulfill, next, x); } - } }, - reject: { value: function(reason) { - if (this._state === PENDING) { - this._state = REJECTED; - this._reason = reason; - var subscribers = this._subscribers; - while (subscribers.length > 0) { - var subscriber = subscribers.shift(); - if (subscriber.onreject) { - _call(subscriber.onreject, - subscriber.next, - reason); - } - else { - subscriber.next.reject(reason); - } - } + else { + next.resolve(x); } - } }, - then: { value: function(onfulfill, onreject) { - if (typeof onfulfill !== 'function') onfulfill = null; - if (typeof onreject !== 'function') onreject = null; - if (onfulfill || onreject) { - var next = new Future(); - if (this._state === FULFILLED) { - if (onfulfill) { - _resolve(onfulfill, onreject, this, next, this._value); + } + + Object.defineProperties(Future.prototype, { + _value: { writable: true }, + _reason: { writable: true }, + _state: { value: PENDING, writable: true }, + resolve: { value: function(value) { + if (this._state === PENDING) { + this._state = FULFILLED; + this._value = value; + var subscribers = this._subscribers; + while (subscribers.length > 0) { + var subscriber = subscribers.shift(); + _resolve(subscriber.onfulfill, + subscriber.onreject, + this, + subscriber.next, + value); } - else { - next.resolve(this._value); + } + } }, + reject: { value: function(reason) { + if (this._state === PENDING) { + this._state = REJECTED; + this._reason = reason; + var subscribers = this._subscribers; + while (subscribers.length > 0) { + var subscriber = subscribers.shift(); + if (subscriber.onreject) { + _call(subscriber.onreject, + subscriber.next, + reason); + } + else { + subscriber.next.reject(reason); + } } } - else if (this._state === REJECTED) { - if (onreject) { - _call(onreject, next, this._reason); + } }, + then: { value: function(onfulfill, onreject) { + if (typeof onfulfill !== 'function') onfulfill = null; + if (typeof onreject !== 'function') onreject = null; + if (onfulfill || onreject) { + var next = new Future(); + if (this._state === FULFILLED) { + if (onfulfill) { + _resolve(onfulfill, onreject, this, next, this._value); + } + else { + next.resolve(this._value); + } + } + else if (this._state === REJECTED) { + if (onreject) { + _call(onreject, next, this._reason); + } + else { + next.reject(this._reason); + } } else { - next.reject(this._reason); + this._subscribers.push({ + onfulfill: onfulfill, + onreject: onreject, + next: next + }); } + return next; + } + return this; + } }, + inspect: { value: function() { + switch (this._state) { + case PENDING: return { state: 'pending' }; + case FULFILLED: return { state: 'fulfilled', value: this._value }; + case REJECTED: return { state: 'rejected', reason: this._reason }; } - else { - this._subscribers.push({ - onfulfill: onfulfill, - onreject: onreject, - next: next + } }, + catchError: { value: function(onreject, test) { + if (typeof test === 'function') { + var self = this; + return this['catch'](function(e) { + if (test(e)) { + return self['catch'](onreject); + } + else { + throw e; + } }); } - return next; - } - return this; - } }, - inspect: { value: function() { - switch (this._state) { - case PENDING: return { state: 'pending' }; - case FULFILLED: return { state: 'fulfilled', value: this._value }; - case REJECTED: return { state: 'rejected', reason: this._reason }; - } - } }, - catchError: { value: function(onreject, test) { - if (typeof test === 'function') { - var self = this; - return this['catch'](function(e) { - if (test(e)) { - return self['catch'](onreject); - } - else { - throw e; + return this['catch'](onreject); + } }, + 'catch': { value: function(onreject) { + return this.then(null, onreject); + } }, + whenComplete: { value: function(action) { + return this.then( + function(v) { + var f = action(); + if (f === undefined) return v; + f = isPromise(f) ? f : value(f); + return f.then(function() { return v; }); + }, + function(e) { + var f = action(); + if (f === undefined) throw e; + f = isPromise(f) ? f : value(f); + return f.then(function() { throw e; }); } - }); - } - return this['catch'](onreject); - } }, - 'catch': { value: function(onreject) { - return this.then(null, onreject); - } }, - whenComplete: { value: function(action) { - return this.then( - function(v) { - var f = action(); - if (f === undefined) return v; - f = isPromise(f) ? f : value(f); - return f.then(function() { return v; }); - }, - function(e) { - var f = action(); - if (f === undefined) throw e; - f = isPromise(f) ? f : value(f); - return f.then(function() { throw e; }); - } - ); - } }, - timeout: { value: function(duration, reason) { - var future = new Future(); - var timeoutId = setTimeout(function() { - future.reject(reason || new TimeoutError('timeout')); - }, duration); - this.whenComplete(function() { clearTimeout(timeoutId); }) - .then(future.resolve, future.reject); - return future; - } }, - delay: { value: function(duration) { - var future = new Future(); - this.then(function(result) { - setTimeout(function() { - future.resolve(result); + ); + } }, + timeout: { value: function(duration, reason) { + var future = new Future(); + var timeoutId = setTimeout(function() { + future.reject(reason || new TimeoutError('timeout')); }, duration); - }, - future.reject); - return future; - } }, - tap: { value: function(onfulfilledSideEffect, thisArg) { - return this.then(function(result) { - onfulfilledSideEffect.call(thisArg, result); - return result; - }); - } }, - spread: { value: function(onfulfilledArray, thisArg) { - return this.then(function(array) { - return onfulfilledArray.apply(thisArg, array); - }); - } }, - get: { value: function(key) { - return this.then(function(result) { - return result[key]; - }); - } }, - set: { value: function(key, value) { - return this.then(function(result) { - result[key] = value; - return result; - }); - } }, - apply: { value: function(method, args) { - args = args || []; - return this.then(function(result) { - return all(args).then(function(args) { - return result[method].apply(result, args); + this.whenComplete(function() { clearTimeout(timeoutId); }) + .then(future.resolve, future.reject); + return future; + } }, + delay: { value: function(duration) { + var future = new Future(); + this.then(function(result) { + setTimeout(function() { + future.resolve(result); + }, duration); + }, + future.reject); + return future; + } }, + tap: { value: function(onfulfilledSideEffect, thisArg) { + return this.then(function(result) { + onfulfilledSideEffect.call(thisArg, result); + return result; }); - }); - } }, - call: { value: function(method) { - var args = slice(arguments, 1); - return this.then(function(result) { - return all(args).then(function(args) { - return result[method].apply(result, args); + } }, + spread: { value: function(onfulfilledArray, thisArg) { + return this.then(function(array) { + return onfulfilledArray.apply(thisArg, array); }); - }); - } }, - bind: { value: function(method) { - var bindargs = slice(arguments); - if (Array.isArray(method)) { - for (var i = 0, n = method.length; i < n; ++i) { - bindargs[0] = method[i]; - this.bind.apply(this, bindargs); - } - return; - } - bindargs.shift(); - var self = this; - Object.defineProperty(this, method, { value: function() { - var args = slice(arguments); - return self.then(function(result) { - return all(bindargs.concat(args)).then(function(args) { + } }, + get: { value: function(key) { + return this.then(function(result) { + return result[key]; + }); + } }, + set: { value: function(key, value) { + return this.then(function(result) { + result[key] = value; + return result; + }); + } }, + apply: { value: function(method, args) { + args = args || []; + return this.then(function(result) { + return all(args).then(function(args) { return result[method].apply(result, args); }); }); - } }); - return this; - } }, - forEach: { value: function(callback, thisArg) { - return forEach(this, callback, thisArg); - } }, - every: { value: function(callback, thisArg) { - return every(this, callback, thisArg); - } }, - some: { value: function(callback, thisArg) { - return some(this, callback, thisArg); - } }, - filter: { value: function(callback, thisArg) { - return filter(this, callback, thisArg); - } }, - map: { value: function(callback, thisArg) { - return map(this, callback, thisArg); - } }, - reduce: { value: function(callback, initialValue) { - if (arguments.length > 1) { - return reduce(this, callback, initialValue); - } - return reduce(this, callback); - } }, - reduceRight: { value: function(callback, initialValue) { - if (arguments.length > 1) { - return reduceRight(this, callback, initialValue); - } - return reduceRight(this, callback); - } } -}); - -global.hprose.Future = Future; - -function Completer() { - var future = new Future(); - Object.defineProperties(this, { - future: { value: future }, - complete: { value: future.resolve }, - completeError: { value: future.reject }, - isCompleted: { get: function() { - return ( future._state !== PENDING ); + } }, + call: { value: function(method) { + var args = slice(arguments, 1); + return this.then(function(result) { + return all(args).then(function(args) { + return result[method].apply(result, args); + }); + }); + } }, + bind: { value: function(method) { + var bindargs = slice(arguments); + if (Array.isArray(method)) { + for (var i = 0, n = method.length; i < n; ++i) { + bindargs[0] = method[i]; + this.bind.apply(this, bindargs); + } + return; + } + bindargs.shift(); + var self = this; + Object.defineProperty(this, method, { value: function() { + var args = slice(arguments); + return self.then(function(result) { + return all(bindargs.concat(args)).then(function(args) { + return result[method].apply(result, args); + }); + }); + } }); + return this; + } }, + forEach: { value: function(callback, thisArg) { + return forEach(this, callback, thisArg); + } }, + every: { value: function(callback, thisArg) { + return every(this, callback, thisArg); + } }, + some: { value: function(callback, thisArg) { + return some(this, callback, thisArg); + } }, + filter: { value: function(callback, thisArg) { + return filter(this, callback, thisArg); + } }, + map: { value: function(callback, thisArg) { + return map(this, callback, thisArg); + } }, + reduce: { value: function(callback, initialValue) { + if (arguments.length > 1) { + return reduce(this, callback, initialValue); + } + return reduce(this, callback); + } }, + reduceRight: { value: function(callback, initialValue) { + if (arguments.length > 1) { + return reduceRight(this, callback, initialValue); + } + return reduceRight(this, callback); } } }); -} -global.hprose.Completer = Completer; + global.hprose.Future = Future; -global.hprose.resolved = value; + function Completer() { + var future = new Future(); + Object.defineProperties(this, { + future: { value: future }, + complete: { value: future.resolve }, + completeError: { value: future.reject }, + isCompleted: { get: function() { + return ( future._state !== PENDING ); + } } + }); + } -global.hprose.rejected = error; + global.hprose.Completer = Completer; -global.hprose.deferred = function() { - var self = new Future(); - return Object.create(null, { - promise: { value: self }, - resolve: { value: self.resolve }, - reject: { value: self.reject }, - }); -}; + global.hprose.resolved = value; -if (hasPromise) return; + global.hprose.rejected = error; -global.Promise = function(executor) { - Future.call(this); - executor(this.resolve, this.reject); -}; + global.hprose.deferred = function() { + var self = new Future(); + return Object.create(null, { + promise: { value: self }, + resolve: { value: self.resolve }, + reject: { value: self.reject }, + }); + }; + + if (hasPromise) return; -global.Promise.prototype = Object.create(Future.prototype); -global.Promise.prototype.constructor = Future; + global.Promise = function(executor) { + Future.call(this); + executor(this.resolve, this.reject); + }; + + global.Promise.prototype = Object.create(Future.prototype); + global.Promise.prototype.constructor = Future; -Object.defineProperties(global.Promise, { - all: { value: all }, - race: { value: race }, - resolve: { value: value }, - reject: { value: error } -}); + Object.defineProperties(global.Promise, { + all: { value: all }, + race: { value: race }, + resolve: { value: value }, + reject: { value: error } + }); +})(); \ No newline at end of file diff --git a/lib/common/HarmonyMaps.js b/lib/common/HarmonyMaps.js index a3f62b5..62e9782 100644 --- a/lib/common/HarmonyMaps.js +++ b/lib/common/HarmonyMaps.js @@ -13,281 +13,284 @@ * * * Harmony Maps for Node.js. * * * - * LastModified: Sep 11, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, unused:false, eqeqeq:true */ -'use strict'; +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ +(function() { + 'use strict'; -var hasWeakMap = 'WeakMap' in global; -var hasMap = 'Map' in global; -var hasForEach = true; + var hasWeakMap = 'WeakMap' in global; + var hasMap = 'Map' in global; + var hasForEach = true; -if (hasMap) { - hasForEach = 'forEach' in new global.Map(); -} + if (hasMap) { + hasForEach = 'forEach' in new global.Map(); + } -if (hasWeakMap && hasMap && hasForEach) return; + if (hasWeakMap && hasMap && hasForEach) return; -var namespaces = Object.create(null); -var count = 0; -var reDefineValueOf = function (obj) { - var privates = Object.create(null); - var baseValueOf = obj.valueOf; - Object.defineProperty(obj, 'valueOf', { - value: function (namespace, n) { - if ((this === obj) && - (n in namespaces) && - (namespaces[n] === namespace)) { - if (!(n in privates)) privates[n] = Object.create(null); - return privates[n]; - } - else { - return baseValueOf.apply(this, arguments); - } - }, - writable: true, - configurable: true, - enumerable: false - }); -}; + var namespaces = Object.create(null); + var count = 0; + var reDefineValueOf = function (obj) { + var privates = Object.create(null); + var baseValueOf = obj.valueOf; + Object.defineProperty(obj, 'valueOf', { + value: function (namespace, n) { + if ((this === obj) && + (n in namespaces) && + (namespaces[n] === namespace)) { + if (!(n in privates)) privates[n] = Object.create(null); + return privates[n]; + } + else { + return baseValueOf.apply(this, arguments); + } + }, + writable: true, + configurable: true, + enumerable: false + }); + }; -if (!hasWeakMap) { - global.WeakMap = function WeakMap() { - var namespace = Object.create(null); - var n = count++; - namespaces[n] = namespace; - var map = function (key) { - if (key !== Object(key)) throw new Error('value is not a non-null object'); - var privates = key.valueOf(namespace, n); - if (privates !== key.valueOf()) return privates; - reDefineValueOf(key); - return key.valueOf(namespace, n); - }; - var m = Object.create(WeakMap.prototype, { - get: { - value: function (key) { - return map(key).value; - } - }, - set: { - value: function (key, value) { - map(key).value = value; - } - }, - has: { - value: function (key) { - return 'value' in map(key); + if (!hasWeakMap) { + global.WeakMap = function WeakMap() { + var namespace = Object.create(null); + var n = count++; + namespaces[n] = namespace; + var map = function (key) { + if (key !== Object(key)) throw new Error('value is not a non-null object'); + var privates = key.valueOf(namespace, n); + if (privates !== key.valueOf()) return privates; + reDefineValueOf(key); + return key.valueOf(namespace, n); + }; + var m = Object.create(WeakMap.prototype, { + get: { + value: function (key) { + return map(key).value; + } + }, + set: { + value: function (key, value) { + map(key).value = value; + } + }, + has: { + value: function (key) { + return 'value' in map(key); + } + }, + 'delete': { + value: function (key) { + return delete map(key).value; + } + }, + clear: { + value: function () { + delete namespaces[n]; + n = count++; + namespaces[n] = namespace; + } } - }, - 'delete': { - value: function (key) { - return delete map(key).value; + }); + if (arguments.length > 0 && Array.isArray(arguments[0])) { + var iterable = arguments[0]; + for (var i = 0, len = iterable.length; i < len; i++) { + m.set(iterable[i][0], iterable[i][1]); } - }, - clear: { - value: function () { + } + return m; + }; + } + + if (!hasMap) { + var objectMap = function () { + var namespace = Object.create(null); + var n = count++; + var nullMap = Object.create(null); + namespaces[n] = namespace; + var map = function (key) { + if (key === null) return nullMap; + var privates = key.valueOf(namespace, n); + if (privates !== key.valueOf()) return privates; + reDefineValueOf(key); + return key.valueOf(namespace, n); + }; + return { + get: function (key) { return map(key).value; }, + set: function (key, value) { map(key).value = value; }, + has: function (key) { return 'value' in map(key); }, + 'delete': function (key) { return delete map(key).value; }, + clear: function () { delete namespaces[n]; n = count++; namespaces[n] = namespace; } - } - }); - if (arguments.length > 0 && Array.isArray(arguments[0])) { - var iterable = arguments[0]; - for (var i = 0, len = iterable.length; i < len; i++) { - m.set(iterable[i][0], iterable[i][1]); - } - } - return m; - }; -} - -if (!hasMap) { - var objectMap = function () { - var namespace = Object.create(null); - var n = count++; - var nullMap = Object.create(null); - namespaces[n] = namespace; - var map = function (key) { - if (key === null) return nullMap; - var privates = key.valueOf(namespace, n); - if (privates !== key.valueOf()) return privates; - reDefineValueOf(key); - return key.valueOf(namespace, n); + }; }; - return { - get: function (key) { return map(key).value; }, - set: function (key, value) { map(key).value = value; }, - has: function (key) { return 'value' in map(key); }, - 'delete': function (key) { return delete map(key).value; }, - clear: function () { - delete namespaces[n]; - n = count++; - namespaces[n] = namespace; - } + var noKeyMap = function () { + var map = Object.create(null); + return { + get: function () { return map.value; }, + set: function (_, value) { map.value = value; }, + has: function () { return 'value' in map; }, + 'delete': function () { return delete map.value; }, + clear: function () { map = Object.create(null); } + }; }; - }; - var noKeyMap = function () { - var map = Object.create(null); - return { - get: function () { return map.value; }, - set: function (_, value) { map.value = value; }, - has: function () { return 'value' in map; }, - 'delete': function () { return delete map.value; }, - clear: function () { map = Object.create(null); } - }; - }; - var scalarMap = function () { - var map = Object.create(null); - return { - get: function (key) { return map[key]; }, - set: function (key, value) { map[key] = value; }, - has: function (key) { return key in map; }, - 'delete': function (key) { return delete map[key]; }, - clear: function () { map = Object.create(null); } + var scalarMap = function () { + var map = Object.create(null); + return { + get: function (key) { return map[key]; }, + set: function (key, value) { map[key] = value; }, + has: function (key) { return key in map; }, + 'delete': function (key) { return delete map[key]; }, + clear: function () { map = Object.create(null); } + }; }; - }; - global.Map = function Map() { - var map = { - 'number': scalarMap(), - 'string': scalarMap(), - 'boolean': scalarMap(), - 'object': objectMap(), - 'function': objectMap(), - 'unknown': objectMap(), - 'undefined': noKeyMap(), - 'null': noKeyMap() - }; - var size = 0; - var keys = []; - var m = Object.create(Map.prototype, { - size: { - get : function () { return size; } - }, - get: { - value: function (key) { - return map[typeof(key)].get(key); - } - }, - set: { - value: function (key, value) { - if (!this.has(key)) { - keys.push(key); - size++; + global.Map = function Map() { + var map = { + 'number': scalarMap(), + 'string': scalarMap(), + 'boolean': scalarMap(), + 'object': objectMap(), + 'function': objectMap(), + 'unknown': objectMap(), + 'undefined': noKeyMap(), + 'null': noKeyMap() + }; + var size = 0; + var keys = []; + var m = Object.create(Map.prototype, { + size: { + get : function () { return size; } + }, + get: { + value: function (key) { + return map[typeof(key)].get(key); } - map[typeof(key)].set(key, value); - } - }, - has: { - value: function (key) { - return map[typeof(key)].has(key); - } - }, - 'delete': { - value: function (key) { - if (this.has(key)) { - size--; - keys.splice(keys.indexOf(key), 1); - return map[typeof(key)]['delete'](key); + }, + set: { + value: function (key, value) { + if (!this.has(key)) { + keys.push(key); + size++; + } + map[typeof(key)].set(key, value); } - return false; - } - }, - clear: { - value: function () { - keys.length = 0; - for (var key in map) map[key].clear(); - size = 0; - } - }, - forEach: { - value: function (callback, thisArg) { - for (var i = 0, n = keys.length; i < n; i++) { - callback.call(thisArg, this.get(keys[i]), keys[i], this); + }, + has: { + value: function (key) { + return map[typeof(key)].has(key); + } + }, + 'delete': { + value: function (key) { + if (this.has(key)) { + size--; + keys.splice(keys.indexOf(key), 1); + return map[typeof(key)]['delete'](key); + } + return false; + } + }, + clear: { + value: function () { + keys.length = 0; + for (var key in map) map[key].clear(); + size = 0; + } + }, + forEach: { + value: function (callback, thisArg) { + for (var i = 0, n = keys.length; i < n; i++) { + callback.call(thisArg, this.get(keys[i]), keys[i], this); + } } } + }); + if (arguments.length > 0 && Array.isArray(arguments[0])) { + var iterable = arguments[0]; + for (var i = 0, len = iterable.length; i < len; i++) { + m.set(iterable[i][0], iterable[i][1]); + } } - }); - if (arguments.length > 0 && Array.isArray(arguments[0])) { - var iterable = arguments[0]; - for (var i = 0, len = iterable.length; i < len; i++) { - m.set(iterable[i][0], iterable[i][1]); - } - } - return m; - }; -} + return m; + }; + } -if (!hasForEach) { - var OldMap = global.Map; - global.Map = function Map() { - var map = new OldMap(); - var size = 0; - var keys = []; - var m = Object.create(Map.prototype, { - size: { - get : function () { return size; } - }, - get: { - value: function (key) { - return map.get(key); - } - }, - set: { - value: function (key, value) { - if (!map.has(key)) { - keys.push(key); - size++; + if (!hasForEach) { + var OldMap = global.Map; + global.Map = function Map() { + var map = new OldMap(); + var size = 0; + var keys = []; + var m = Object.create(Map.prototype, { + size: { + get : function () { return size; } + }, + get: { + value: function (key) { + return map.get(key); } - map.set(key, value); - } - }, - has: { - value: function (key) { - return map.has(key); - } - }, - 'delete': { - value: function (key) { - if (map.has(key)) { - size--; - keys.splice(keys.indexOf(key), 1); - return map['delete'](key); + }, + set: { + value: function (key, value) { + if (!map.has(key)) { + keys.push(key); + size++; + } + map.set(key, value); } - return false; - } - }, - clear: { - value: function () { - if ('clear' in map) { - map.clear(); + }, + has: { + value: function (key) { + return map.has(key); } - else { + }, + 'delete': { + value: function (key) { + if (map.has(key)) { + size--; + keys.splice(keys.indexOf(key), 1); + return map['delete'](key); + } + return false; + } + }, + clear: { + value: function () { + if ('clear' in map) { + map.clear(); + } + else { + for (var i = 0, n = keys.length; i < n; i++) { + map['delete'](keys[i]); + } + } + keys.length = 0; + size = 0; + } + }, + forEach: { + value: function (callback, thisArg) { for (var i = 0, n = keys.length; i < n; i++) { - map['delete'](keys[i]); + callback.call(thisArg, this.get(keys[i]), keys[i], this); } } - keys.length = 0; - size = 0; } - }, - forEach: { - value: function (callback, thisArg) { - for (var i = 0, n = keys.length; i < n; i++) { - callback.call(thisArg, this.get(keys[i]), keys[i], this); - } + }); + if (arguments.length > 0 && Array.isArray(arguments[0])) { + var iterable = arguments[0]; + for (var i = 0, len = iterable.length; i < len; i++) { + m.set(iterable[i][0], iterable[i][1]); } } - }); - if (arguments.length > 0 && Array.isArray(arguments[0])) { - var iterable = arguments[0]; - for (var i = 0, len = iterable.length; i < len; i++) { - m.set(iterable[i][0], iterable[i][1]); - } - } - return m; - }; -} + return m; + }; + } +})(); \ No newline at end of file diff --git a/lib/common/ResultMode.js b/lib/common/ResultMode.js index 353c83c..6979401 100644 --- a/lib/common/ResultMode.js +++ b/lib/common/ResultMode.js @@ -13,12 +13,13 @@ * * * Hprose ResultMode for Node.js. * * * - * LastModified: May 15, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; global.hprose.ResultMode = { diff --git a/lib/common/setImmediate.js b/lib/common/setImmediate.js index 6fe032d..d0ae905 100644 --- a/lib/common/setImmediate.js +++ b/lib/common/setImmediate.js @@ -13,60 +13,55 @@ * * * setImmediate for Node.js. * * * - * LastModified: Jul 19, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ -'use strict'; +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ +(function() { + 'use strict'; -if (global.setImmediate) return; + if (global.setImmediate) return; -var slice = Function.prototype.call.bind(Array.prototype.slice); -var nextId = 1; -var tasks = {}; -var lock = false; + var slice = Function.prototype.call.bind(Array.prototype.slice); + var nextId = 1; + var tasks = {}; -function wrap(handler) { - var args = slice(arguments, 1); - return function() { - handler.apply(undefined, args); - }; -} - -function run(handleId) { - if (lock) { - global.setTimeout(wrap(run, handleId), 0); + function wrap(handler) { + var args = slice(arguments, 1); + return function() { + handler.apply(undefined, args); + }; } - else { + + function run(handleId) { var task = tasks[handleId]; if (task) { - lock = true; try { task(); } finally { clear(handleId); - lock = false; } } } -} -function create(args) { - tasks[nextId] = wrap.apply(undefined, args); - return nextId++; -} + function create(args) { + tasks[nextId] = wrap.apply(undefined, args); + return nextId++; + } -function clear(handleId) { - delete tasks[handleId]; -} + function clear(handleId) { + delete tasks[handleId]; + } -global.setImmediate = function() { - var handleId = create(arguments); - global.process.nextTick( wrap( run, handleId ) ); - return handleId; -}; + global.setImmediate = function() { + var handleId = create(arguments); + global.process.nextTick( wrap( run, handleId ) ); + return handleId; + }; -global.clearImmediate = clear; + global.clearImmediate = clear; +})(); diff --git a/lib/filter/JSONRPCClientFilter.js b/lib/filter/JSONRPCClientFilter.js index fccde74..12ae7e0 100644 --- a/lib/filter/JSONRPCClientFilter.js +++ b/lib/filter/JSONRPCClientFilter.js @@ -13,12 +13,13 @@ * * * jsonrpc client filter for Node.js. * * * - * LastModified: Jul 17, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var Tags = global.hprose.Tags; diff --git a/lib/filter/JSONRPCServiceFilter.js b/lib/filter/JSONRPCServiceFilter.js index d966687..309c0ea 100644 --- a/lib/filter/JSONRPCServiceFilter.js +++ b/lib/filter/JSONRPCServiceFilter.js @@ -13,12 +13,13 @@ * * * jsonrpc service filter for Node.js. * * * - * LastModified: May 21, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var Tags = global.hprose.Tags; diff --git a/lib/hprose.js b/lib/hprose.js index 0e1d19d..1f7d229 100644 --- a/lib/hprose.js +++ b/lib/hprose.js @@ -13,12 +13,13 @@ * * * hprose for Node.js. * * * - * LastModified: Jun 22, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; global.hprose = global.hprose || Object.create(null); diff --git a/lib/io/BytesIO.js b/lib/io/BytesIO.js index e03f5b3..72ffe77 100644 --- a/lib/io/BytesIO.js +++ b/lib/io/BytesIO.js @@ -13,12 +13,13 @@ * * * Hprose BytesIO for Node.js. * * * - * LastModified: Feb 22, 2016 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var _EMPTY_BYTES = new Uint8Array(0); diff --git a/lib/io/ClassManager.js b/lib/io/ClassManager.js index 042d538..67fa6cd 100644 --- a/lib/io/ClassManager.js +++ b/lib/io/ClassManager.js @@ -13,12 +13,13 @@ * * * hprose ClassManager for Node.js. * * * - * LastModified: May 15, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var WeakMap = global.WeakMap; diff --git a/lib/io/Formatter.js b/lib/io/Formatter.js index 271ddb2..ef12aee 100644 --- a/lib/io/Formatter.js +++ b/lib/io/Formatter.js @@ -13,12 +13,13 @@ * * * Hprose Formatter for Node.js. * * * - * LastModified: May 15, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var BytesIO = global.hprose.BytesIO; diff --git a/lib/io/Reader.js b/lib/io/Reader.js index 5422ab6..9c190ff 100644 --- a/lib/io/Reader.js +++ b/lib/io/Reader.js @@ -13,13 +13,13 @@ * * * Hprose Reader for Node.js. * * * - * LastModified: Aug 3, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ -/*jshint unused:false */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var Map = global.Map; diff --git a/lib/io/Tags.js b/lib/io/Tags.js index a00bb62..3ca3a2b 100644 --- a/lib/io/Tags.js +++ b/lib/io/Tags.js @@ -13,12 +13,13 @@ * * * Hprose Tags for Node.js. * * * - * LastModified: May 15, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; global.hprose.Tags = { diff --git a/lib/io/Writer.js b/lib/io/Writer.js index 40f28bb..3e004d6 100644 --- a/lib/io/Writer.js +++ b/lib/io/Writer.js @@ -13,12 +13,13 @@ * * * Hprose Writer for Node.js. * * * - * LastModified: Sep 11, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true, unused:false */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var Map = global.Map; diff --git a/lib/server/HttpServer.js b/lib/server/HttpServer.js index 5334b5c..72f9db7 100644 --- a/lib/server/HttpServer.js +++ b/lib/server/HttpServer.js @@ -13,12 +13,13 @@ * * * Hprose Http Server for Node.js. * * * - * LastModified: Aug 9, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); diff --git a/lib/server/HttpService.js b/lib/server/HttpService.js index bf8626b..46ccc3f 100644 --- a/lib/server/HttpService.js +++ b/lib/server/HttpService.js @@ -13,12 +13,13 @@ * * * Hprose Http Service for Node.js. * * * - * LastModified: Aug 10, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var fs = require('fs'); diff --git a/lib/server/Server.js b/lib/server/Server.js index 14802db..dee5c7d 100644 --- a/lib/server/Server.js +++ b/lib/server/Server.js @@ -13,12 +13,13 @@ * * * Hprose Server for Node.js. * * * - * LastModified: Jun 20, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var parse = require('url').parse; diff --git a/lib/server/Service.js b/lib/server/Service.js index 1a06542..0761c2c 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,12 +13,13 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Dec 13, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); diff --git a/lib/server/SocketServer.js b/lib/server/SocketServer.js index c09dbe6..e620654 100644 --- a/lib/server/SocketServer.js +++ b/lib/server/SocketServer.js @@ -13,12 +13,13 @@ * * * Hprose Socket Server for Node.js. * * * - * LastModified: Aug 9, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); diff --git a/lib/server/SocketService.js b/lib/server/SocketService.js index 841f13a..9466011 100644 --- a/lib/server/SocketService.js +++ b/lib/server/SocketService.js @@ -13,12 +13,13 @@ * * * Hprose Socket Service for Node.js. * * * - * LastModified: Aug 9, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); diff --git a/lib/server/WebSocketServer.js b/lib/server/WebSocketServer.js index ae1d74c..d2ebcb0 100644 --- a/lib/server/WebSocketServer.js +++ b/lib/server/WebSocketServer.js @@ -13,12 +13,13 @@ * * * Hprose WebSocket Server for Node.js. * * * - * LastModified: Aug 9, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); diff --git a/lib/server/WebSocketService.js b/lib/server/WebSocketService.js index 28faf3e..c30f2c6 100644 --- a/lib/server/WebSocketService.js +++ b/lib/server/WebSocketService.js @@ -13,12 +13,13 @@ * * * Hprose WebSocket Service for Node.js. * * * - * LastModified: Aug 9, 2015 * + * LastModified: Feb 25, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*jshint node:true, eqeqeq:true */ +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); @@ -114,8 +115,6 @@ function WebSocketService() { } catch(e) {} }); - var bytes = new BytesIO(); - var dataLength = -1; ws.on('error', function(e) { try { self.emit('sendError', e, context); From daaab0752935a4c1eaec9bb4c7b2ba80e8a4e815 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 25 Feb 2016 23:22:09 +0800 Subject: [PATCH 011/131] Removed onError --- lib/client/Client.js | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index d6b4fa0..443dc8b 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -1099,7 +1099,6 @@ function Client(uri, functions, settings) { }); Object.defineProperties(this, { '#': { value: autoId }, - onError: { get: getOnError, set: setOnError }, onerror: { get: getOnError, set: setOnError }, uri: { get: getUri }, id: { get: getId }, From 2f99d00397531fbff9683f843db0d1172681a01a Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 28 Feb 2016 15:52:47 +0800 Subject: [PATCH 012/131] Fixed a few bugs. --- lib/client/HttpClient.js | 2 +- lib/client/SocketClient.js | 4 ++-- lib/client/WebSocketClient.js | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/client/HttpClient.js b/lib/client/HttpClient.js index eee802a..eb90105 100644 --- a/lib/client/HttpClient.js +++ b/lib/client/HttpClient.js @@ -234,7 +234,7 @@ function create(uri, functions, settings) { uri.forEach(function(uri) { checkuri(uri); }); } else { - return new Error('You should set server uri first!'); + throw new Error('You should set server uri first!'); } return new HttpClient(uri, functions, settings); } diff --git a/lib/client/SocketClient.js b/lib/client/SocketClient.js index e6e4d8a..9f707fc 100644 --- a/lib/client/SocketClient.js +++ b/lib/client/SocketClient.js @@ -13,7 +13,7 @@ * * * Hprose Socket Client for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Feb 28, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -469,7 +469,7 @@ function create(uri, functions, settings) { uri.forEach(function(uri) { checkuri(uri); }); } else { - return new Error('You should set server uri first!'); + throw new Error('You should set server uri first!'); } return new SocketClient(uri, functions, settings); } diff --git a/lib/client/WebSocketClient.js b/lib/client/WebSocketClient.js index 8fde22d..95bf34d 100644 --- a/lib/client/WebSocketClient.js +++ b/lib/client/WebSocketClient.js @@ -12,7 +12,7 @@ * * * Hprose WebSocket Client for HTML5. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Feb 28, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -170,7 +170,7 @@ function create(uri, functions, settings) { uri.forEach(function(uri) { checkuri(uri); }); } else { - return new Error('You should set server uri first!'); + throw new Error('You should set server uri first!'); } return new WebSocketClient(uri, functions, settings); } From e20a8fa1d2c19b9d1f6cc666d38b10be4c3cd7c5 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 2 Mar 2016 16:42:16 +0800 Subject: [PATCH 013/131] Added some helper methods. --- lib/common/Helper.js | 89 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 lib/common/Helper.js diff --git a/lib/common/Helper.js b/lib/common/Helper.js new file mode 100644 index 0000000..56ed74e --- /dev/null +++ b/lib/common/Helper.js @@ -0,0 +1,89 @@ +/**********************************************************\ +| | +| hprose | +| | +| Official WebSite: http://www.hprose.com/ | +| http://www.hprose.org/ | +| | +\**********************************************************/ + +/**********************************************************\ + * * + * hprose/common/Helper.js * + * * + * Hprose Helper for Node.js. * + * * + * LastModified: Mar 2, 2016 * + * Author: Ma Bingyao * + * * +\**********************************************************/ + +/*global global */ +/*jshint node:true, noused:true, eqeqeq:true */ +(function() { + 'use strict'; + + function generic(method) { + if (typeof method !== "function") { + throw new TypeError(method + " is not a function"); + } + return function(context) { + return method.apply(context, Array.prototype.slice.call(arguments, 1)); + }; + } + + var arrayLikeObjectArgumentsEnabled = true; + + try { + String.fromCharCode.apply(String, new Uint8Array([1])); + } + catch (e) { + arrayLikeObjectArgumentsEnabled = false; + } + + function toArray(arrayLikeObject) { + var n = arrayLikeObject.length; + var a = new Array(n); + for (var i = 0; i < n; ++i) { + a[i] = arrayLikeObject[i]; + } + return a; + } + + var getCharCodes = arrayLikeObjectArgumentsEnabled ? function(bytes) { return bytes; } : toArray; + + function toBinaryString(bytes) { + if (bytes instanceof ArrayBuffer) { + bytes = new Uint8Array(bytes); + } + var n = bytes.length; + if (n < 100000) { + return String.fromCharCode.apply(String, getCharCodes(bytes)); + } + var remain = n & 0xFFFF; + var count = n >> 16; + var a = new Array(remain ? count + 1 : count); + for (var i = 0; i < count; ++i) { + a[i] = String.fromCharCode.apply(String, getCharCodes(bytes.subarray(i << 16, (i + 1) << 16))); + } + if (remain) { + a[count] = String.fromCharCode.apply(String, getCharCodes(bytes.subarray(count << 16, n))); + } + return a.join(''); + } + + function toUint8Array(bs) { + var n = bs.length; + var data = new Uint8Array(n); + for (var i = 0; i < n; i++) { + data[i] = bs.charCodeAt(i) & 0xFF; + } + return data; + } + + global.hprose.generic = generic; + global.hprose.toBinaryString = toBinaryString; + global.hprose.toUint8Array = toUint8Array; + global.hprose.toArray = toArray; + +})(); From e668993b7015321e4e68e2dae4f832aa9b0fb132 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 2 Mar 2016 16:42:39 +0800 Subject: [PATCH 014/131] Added filters property for Client --- lib/client/Client.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/client/Client.js b/lib/client/Client.js index 443dc8b..66efb8a 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -778,6 +778,9 @@ function Client(uri, functions, settings) { _filters.splice(i, 1); return true; } + function filters() { + return _filters; + } function useService(uri, functions, create) { if (create === undefined) { if (typeof(functions) === s_boolean) { @@ -1115,6 +1118,7 @@ function Client(uri, functions, settings) { filter: { get: getFilter, set: setFilter }, addFilter: { value: addFilter }, removeFilter: { value: removeFilter }, + filters: { get: filters }, useService: { value: useService }, invoke: { value: invoke }, ready: { value: ready }, From ac2235e1e5ab6a33dd288293749452f429c5e30c Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 2 Mar 2016 16:43:29 +0800 Subject: [PATCH 015/131] Added indexOf, lastIndexOf, includes, find, findIndex method on Future and Future.prototype --- lib/common/Future.js | 69 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 2 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index b5e0fc8..4b23cae 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 2, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -279,6 +279,51 @@ }); } + function indexOf(array, searchElement, fromIndex) { + return all(array).then(function(array) { + if (!isPromise(searchElement)) { + searchElement = value(searchElement); + } + return searchElement.then(function(searchElement) { + return array.indexOf(searchElement, fromIndex); + }); + }); + } + + function lastIndexOf(array, searchElement, fromIndex) { + return all(array).then(function(array) { + if (!isPromise(searchElement)) { + searchElement = value(searchElement); + } + return searchElement.then(function(searchElement) { + return array.lastIndexOf(searchElement, fromIndex); + }); + }); + } + + function includes(array, searchElement, fromIndex) { + return all(array).then(function(array) { + if (!isPromise(searchElement)) { + searchElement = value(searchElement); + } + return searchElement.then(function(searchElement) { + return array.includes(searchElement, fromIndex); + }); + }); + } + + function find(array, predicate, thisArg) { + return all(array).then(function(array) { + return array.find(predicate, thisArg); + }); + } + + function findIndex(array, predicate, thisArg) { + return all(array).then(function(array) { + return array.findIndex(predicate, thisArg); + }); + } + Object.defineProperties(Future, { // port from Dart delayed: { value: delayed }, @@ -307,7 +352,12 @@ filter: { value: filter }, map: { value: map }, reduce: { value: reduce }, - reduceRight: { value: reduceRight } + reduceRight: { value: reduceRight }, + indexOf: { value: indexOf }, + lastIndexOf: { value: lastIndexOf }, + includes: { value: includes }, + find: { value: find }, + findIndex: { value: findIndex } }); function _call(callback, next, x) { @@ -604,6 +654,21 @@ return reduceRight(this, callback, initialValue); } return reduceRight(this, callback); + } }, + indexOf: { value: function(searchElement, fromIndex) { + return indexOf(this, searchElement, fromIndex); + } }, + lastIndexOf: { value: function(searchElement, fromIndex) { + return lastIndexOf(this, searchElement, fromIndex); + } }, + includes: { value: function(searchElement, fromIndex) { + return includes(this, searchElement, fromIndex); + } }, + find: { value: function(predicate, thisArg) { + return find(this, predicate, thisArg); + } }, + findIndex: { value: function(predicate, thisArg) { + return findIndex(this, predicate, thisArg); } } }); From 1e41d40e47349d1865b1e3d67fe9fcd1bb602476 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 2 Mar 2016 16:43:48 +0800 Subject: [PATCH 016/131] Update BytesIO --- lib/io/BytesIO.js | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/lib/io/BytesIO.js b/lib/io/BytesIO.js index 72ffe77..939adba 100644 --- a/lib/io/BytesIO.js +++ b/lib/io/BytesIO.js @@ -13,7 +13,7 @@ * * * Hprose BytesIO for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 2, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -22,6 +22,8 @@ /*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; +var toBinaryString = global.hprose.toBinaryString; + var _EMPTY_BYTES = new Uint8Array(0); var _INIT_SIZE = 1024; var indexof = Function.prototype.call.bind(Array.prototype.indexOf); @@ -552,20 +554,7 @@ Object.defineProperties(BytesIO.prototype, { n = this._length - this._off; } if (n === 0) return ''; - var bytes = this._bytes.subarray(this._off, this._off += n); - if (n < 100000) { - return String.fromCharCode.apply(String, bytes); - } - var remain = n & 0xFFFF; - var count = n >> 16; - var a = new Array(remain ? count + 1 : count); - for (var i = 0; i < count; ++i) { - a[i] = String.fromCharCode.apply(String, bytes.subarray(i << 16, (i + 1) << 16)); - } - if (remain) { - a[count] = String.fromCharCode.apply(String, bytes.subarray(count << 16, n)); - } - return a.join(''); + return toBinaryString(this._bytes.subarray(this._off, this._off += n)); } }, // n is the UTF16 length readStringAsBytes: { value: function(n) { @@ -643,4 +632,4 @@ Object.defineProperties(BytesIO, { toBuffer: { value: toBuffer } }); -global.hprose.BytesIO = BytesIO; +global.hprose.BytesIO = BytesIO; \ No newline at end of file From 798f9c66de28e0fba77507618169857be9a26a1b Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 2 Mar 2016 16:44:02 +0800 Subject: [PATCH 017/131] Added Helper.js --- lib/hprose.js | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/hprose.js b/lib/hprose.js index 1f7d229..3b60192 100644 --- a/lib/hprose.js +++ b/lib/hprose.js @@ -24,6 +24,7 @@ global.hprose = global.hprose || Object.create(null); +require('./common/Helper.js'); require('./common/HarmonyMaps.js'); require('./common/setImmediate.js'); require('./common/Future.js'); From 8951329ac1fb21a8d491cca39c6542a76c5659e4 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 2 Mar 2016 16:44:13 +0800 Subject: [PATCH 018/131] Update tcpserver example --- example/tcpserver.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/example/tcpserver.js b/example/tcpserver.js index aeeff31..f029378 100644 --- a/example/tcpserver.js +++ b/example/tcpserver.js @@ -10,7 +10,7 @@ function hello(name, context) { } function hello2(name) { - return 'Hello ' + name + '!'; + return name; } function asyncHello(name, callback) { @@ -29,11 +29,21 @@ function getMaps() { function LogFilter() { this.inputFilter = function(value) { - console.log(hprose.BytesIO.toString(value)); + try { + console.log(hprose.BytesIO.toString(value)); + } + catch(e) { + console.log(hprose.toBinaryString(value)); + } return value; }; this.outputFilter = function(value) { - console.log(hprose.BytesIO.toString(value)); + try { + console.log(hprose.BytesIO.toString(value)); + } + catch(e) { + console.log(hprose.toBinaryString(value)); + } return value; }; } From 01b03f212a37deeb9add1985d40af25639c6f4f5 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 3 Mar 2016 19:34:41 +0800 Subject: [PATCH 019/131] Added .jshintrc and Fixed some bugs. --- .jshintrc | 26 ++ lib/client/Client.js | 40 ++- lib/client/HttpClient.js | 11 +- lib/client/SocketClient.js | 10 +- lib/client/WebSocketClient.js | 16 +- lib/common/Future.js | 22 +- lib/common/HarmonyMaps.js | 26 +- lib/common/Helper.js | 4 +- lib/common/Polyfill.js | 413 +++++++++++++++++++++++++++++ lib/common/ResultMode.js | 4 +- lib/common/setImmediate.js | 6 +- lib/filter/JSONRPCClientFilter.js | 9 +- lib/filter/JSONRPCServiceFilter.js | 5 +- lib/hprose.js | 5 +- lib/io/BytesIO.js | 31 +-- lib/io/ClassManager.js | 4 +- lib/io/Formatter.js | 4 +- lib/io/Reader.js | 12 +- lib/io/Tags.js | 4 +- lib/io/Writer.js | 86 ++++-- lib/server/HttpServer.js | 4 +- lib/server/HttpService.js | 18 +- lib/server/Server.js | 10 +- lib/server/Service.js | 31 ++- lib/server/SocketServer.js | 4 +- lib/server/SocketService.js | 13 +- lib/server/WebSocketServer.js | 6 +- lib/server/WebSocketService.js | 8 +- package.json | 2 +- 29 files changed, 630 insertions(+), 204 deletions(-) create mode 100644 .jshintrc create mode 100644 lib/common/Polyfill.js diff --git a/.jshintrc b/.jshintrc new file mode 100644 index 0000000..018eaf3 --- /dev/null +++ b/.jshintrc @@ -0,0 +1,26 @@ +{ + "node":true, + "sub":true, + "laxbreak":true, + "laxcomma":true, + "regexp":true, + "asi": true, + "browser": true, + "loopfunc":true, + "expr":true, + "es3": true, + "esnext": true, + "curly": true, + "immed": true, + "latedef": false, + "expr": true, + "eqeqeq": false, + "eqnull": false, + "newcap": true, + "noarg": true, + "undef": true, + "unused": true, + "proto": true, + "strict": false, + "smarttabs": true +} diff --git a/lib/client/Client.js b/lib/client/Client.js index 66efb8a..5e18e62 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,13 +13,12 @@ * * * HproseClient for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global, Proxy */ -/*jshint node:true, noused:true, eqeqeq:true */ +/* global Proxy */ 'use strict'; var util = require('util'); @@ -45,11 +44,10 @@ var s_string = 'string'; var s_number = 'number'; var s_function = 'function'; var s_object = 'object'; -var s_undefined = 'undefined'; function HproseProxy(setFunction, ns) { this.get = function(proxy, name) { - if (ns) name = ns + '_' + name; + if (ns) { name = ns + '_' + name; } return Proxy.createFunction( new HproseProxy(setFunction, name), setFunction(this, name) @@ -111,7 +109,7 @@ function Client(uri, functions, settings) { request = outputFilter(request, context); return _afterFilterHandler(request, context) .then(function(response) { - if (context.oneway) return; + if (context.oneway) { return; } return inputFilter(response, context); }); } @@ -123,7 +121,7 @@ function Client(uri, functions, settings) { function sendAndReceive(request, context, onsuccess, onerror) { _beforeFilterHandler(request, context) .then(onsuccess, function(e) { - if (retry(request, context, onsuccess, onerror)) return; + if (retry(request, context, onsuccess, onerror)) { return; } onerror(e); }); } @@ -203,7 +201,7 @@ function Client(uri, functions, settings) { } function setMethods(stub, obj, namespace, name, methods) { - if (obj[name] !== undefined) return; + if (obj[name] !== undefined) { return; } obj[name] = {}; if (typeof(methods) === s_string || methods.constructor === Object) { methods = [methods]; @@ -241,7 +239,7 @@ function Client(uri, functions, settings) { function copyargs(src, dest) { var n = Math.min(src.length, dest.length); - for (var i = 0; i < n; ++i) dest[i] = src[i]; + for (var i = 0; i < n; ++i) { dest[i] = src[i]; } } function initContext(batch) { @@ -287,9 +285,9 @@ function Client(uri, functions, settings) { } var i = 0, n = args.length; for (; i < n; ++i) { - if (typeof args[i] === s_function) break; + if (typeof args[i] === s_function) { break; } } - if (i === n) return context; + if (i === n) { return context; } var extra = args.splice(i, n - i); context.onsuccess = extra[0]; n = extra.length; @@ -448,7 +446,7 @@ function Client(uri, functions, settings) { } function call(name, args, context) { - if (context.sync) _lock = true; + if (context.sync) { _lock = true; } var promise = Future.promise(function(resolve, reject) { _invokeHandler(name, args, context).then(function(result) { try { @@ -614,9 +612,9 @@ function Client(uri, functions, settings) { }); } var batchSize = _batches.length; - if (batchSize === 0) return; + if (batchSize === 0) { return Future.value([]); } var context = getBatchContext(settings); - if (context.sync) _lock = true; + if (context.sync) { _lock = true; } var batches = _batches; _batches = []; var promise = Future.promise(function(resolve, reject) { @@ -831,7 +829,7 @@ function Client(uri, functions, settings) { if ((argc < 1) || (typeof name !== s_string)) { throw new Error('name must be a string'); } - if (argc === 1) args = []; + if (argc === 1) { args = []; } if (argc === 2) { if (!Array.isArray(args)) { var _args = []; @@ -902,7 +900,7 @@ function Client(uri, functions, settings) { }); return; } - if (timeout === undefined) timeout = _timeout; + if (timeout === undefined) { timeout = _timeout; } var topic = getTopic(name, id, true); if (topic === null) { var cb = function() { @@ -925,7 +923,7 @@ function Client(uri, functions, settings) { catch (e) {} } } - if (getTopic(name, id, false) !== null) cb(); + if (getTopic(name, id, false) !== null) { cb(); } } }, callbacks: [callback] @@ -1019,7 +1017,7 @@ function Client(uri, functions, settings) { return function(name, args, context) { try { var result = handler(name, args, context, next); - if (Future.isFuture(result)) return result; + if (Future.isFuture(result)) { return result; } return Future.value(result); } catch (e) { @@ -1035,7 +1033,7 @@ function Client(uri, functions, settings) { return function(batches, context) { try { var result = handler(batches, context, next); - if (Future.isFuture(result)) return result; + if (Future.isFuture(result)) { return result; } return Future.value(result); } catch (e) { @@ -1051,7 +1049,7 @@ function Client(uri, functions, settings) { return function(request, context) { try { var response = handler(request, context, next); - if (Future.isFuture(response)) return response; + if (Future.isFuture(response)) { return response; } return Future.value(response); } catch (e) { @@ -1067,7 +1065,7 @@ function Client(uri, functions, settings) { return function(request, context) { try { var response = handler(request, context, next); - if (Future.isFuture(response)) return response; + if (Future.isFuture(response)) { return response; } return Future.value(response); } catch (e) { diff --git a/lib/client/HttpClient.js b/lib/client/HttpClient.js index eb90105..dc36ba8 100644 --- a/lib/client/HttpClient.js +++ b/lib/client/HttpClient.js @@ -13,13 +13,11 @@ * * * Hprose Http Client for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); @@ -28,7 +26,6 @@ var https = require('https'); var parse = require('url').parse; var TimeoutError = require('../common/TimeoutError'); -var setImmediate = global.setImmediate; var Client = global.hprose.Client; var BytesIO = global.hprose.BytesIO; var Future = global.hprose.Future; @@ -44,12 +41,12 @@ function setCookie(headers, host) { cookies = value.replace(/(^\s*)|(\s*$)/g, '').split(';'); cookie = {}; value = cookies[0].replace(/(^\s*)|(\s*$)/g, '').split('=', 2); - if (value[1] === undefined) value[1] = null; + if (value[1] === undefined) { value[1] = null; } cookie.name = value[0]; cookie.value = value[1]; for (i = 1; i < cookies.length; i++) { value = cookies[i].replace(/(^\s*)|(\s*$)/g, '').split('=', 2); - if (value[1] === undefined) value[1] = null; + if (value[1] === undefined) { value[1] = null; } cookie[value[0].toUpperCase()] = value[1]; } // Tomcat can return SetCookie2 with path wrapped in " @@ -194,7 +191,7 @@ function HttpClient(uri, functions, settings) { return e instanceof TimeoutError; }); } - if (env.oneway) future.resolve(); + if (env.oneway) { future.resolve(); } return future; } diff --git a/lib/client/SocketClient.js b/lib/client/SocketClient.js index 9f707fc..407a663 100644 --- a/lib/client/SocketClient.js +++ b/lib/client/SocketClient.js @@ -13,13 +13,11 @@ * * * Hprose Socket Client for Node.js. * * * - * LastModified: Feb 28, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); @@ -89,7 +87,7 @@ Object.defineProperties(SocketTransporter.prototype, { protocol === 'tcp6:') { socket = net; options.host = parser.hostname; - options.port = parseInt(parser.port); + options.port = parseInt(parser.port, 10); if (protocol === 'tcp4:') { options.family = 4; } @@ -103,7 +101,7 @@ Object.defineProperties(SocketTransporter.prototype, { protocol === 'tls:') { socket = tls; options.host = parser.hostname; - options.port = parseInt(parser.port); + options.port = parseInt(parser.port, 10); if (protocol === 'tcp4s:') { options.family = 4; } @@ -433,7 +431,7 @@ function SocketClient(uri, functions, settings) { } hdtrans.sendAndReceive(request, future, env); } - if (env.oneway) future.resolve(); + if (env.oneway) { future.resolve(); } return future; } diff --git a/lib/client/WebSocketClient.js b/lib/client/WebSocketClient.js index 95bf34d..b990366 100644 --- a/lib/client/WebSocketClient.js +++ b/lib/client/WebSocketClient.js @@ -12,17 +12,17 @@ * * * Hprose WebSocket Client for HTML5. * * * - * LastModified: Feb 28, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); var parse = require('url').parse; + +/*jshint -W079*/ var WebSocket = require('ws'); var Client = global.hprose.Client; @@ -30,8 +30,6 @@ var BytesIO = global.hprose.BytesIO; var Future = global.hprose.Future; var TimeoutError = require('../common/TimeoutError'); -function noop(){} - function WebSocketClient(uri, functions, settings) { if (this.constructor !== WebSocketClient) { return new WebSocketClient(uri, functions, settings); @@ -71,7 +69,7 @@ function WebSocketClient(uri, functions, settings) { function onopen() { _ready.resolve(); } - function onmessage(data, flags) { + function onmessage(data) { var bytes = new BytesIO(data); var id = bytes.readInt32BE(); var future = _futures[id]; @@ -86,7 +84,7 @@ function WebSocketClient(uri, functions, settings) { _ready.then(function() { send(request[0], request[1]); }); } if (_count === 0) { - if (!self.keepAlive) close(); + if (!self.keepAlive) { close(); } } } function onclose(code, message) { @@ -135,7 +133,7 @@ function WebSocketClient(uri, functions, settings) { else { _requests.push([id, request]); } - if (env.oneway) future.resolve(); + if (env.oneway) { future.resolve(); } return future; } function close() { @@ -149,7 +147,7 @@ function WebSocketClient(uri, functions, settings) { } Object.defineProperties(this, { sendAndReceive: { value: sendAndReceive }, - close: { value: close }, + close: { value: close } }); } diff --git a/lib/common/Future.js b/lib/common/Future.js index 4b23cae..9311811 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -18,8 +18,6 @@ * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ (function() { 'use strict'; @@ -40,7 +38,7 @@ Object.defineProperties(this, { _subscribers: { value: [] }, resolve: { value: this.resolve.bind(this) }, - reject: { value: this.reject.bind(this) }, + reject: { value: this.reject.bind(this) } }); var self = this; if (typeof computation === 'function') { @@ -119,7 +117,7 @@ var n = array.length; var count = arraysize(array); var result = new Array(n); - if (count === 0) return value(result); + if (count === 0) { return value(result); } var future = new Future(); foreach(array, function(element, index) { var f = (isPromise(element) ? element : value(element)); @@ -180,7 +178,7 @@ var n = array.length; var count = arraysize(array); var result = new Array(n); - if (count === 0) return value(result); + if (count === 0) { return value(result); } var future = new Future(); foreach(array, function(element, index) { var f = (isPromise(element) ? element : value(element)); @@ -479,8 +477,8 @@ } } }, then: { value: function(onfulfill, onreject) { - if (typeof onfulfill !== 'function') onfulfill = null; - if (typeof onreject !== 'function') onreject = null; + if (typeof onfulfill !== 'function') { onfulfill = null; } + if (typeof onreject !== 'function') { onreject = null; } if (onfulfill || onreject) { var next = new Future(); if (this._state === FULFILLED) { @@ -538,13 +536,13 @@ return this.then( function(v) { var f = action(); - if (f === undefined) return v; + if (f === undefined) { return v; } f = isPromise(f) ? f : value(f); return f.then(function() { return v; }); }, function(e) { var f = action(); - if (f === undefined) throw e; + if (f === undefined) { throw e; } f = isPromise(f) ? f : value(f); return f.then(function() { throw e; }); } @@ -697,11 +695,11 @@ return Object.create(null, { promise: { value: self }, resolve: { value: self.resolve }, - reject: { value: self.reject }, + reject: { value: self.reject } }); }; - if (hasPromise) return; + if (hasPromise) { return; } global.Promise = function(executor) { Future.call(this); @@ -717,4 +715,4 @@ resolve: { value: value }, reject: { value: error } }); -})(); \ No newline at end of file +})(); diff --git a/lib/common/HarmonyMaps.js b/lib/common/HarmonyMaps.js index 62e9782..e3a2771 100644 --- a/lib/common/HarmonyMaps.js +++ b/lib/common/HarmonyMaps.js @@ -13,13 +13,11 @@ * * * Harmony Maps for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ (function() { 'use strict'; @@ -31,7 +29,7 @@ hasForEach = 'forEach' in new global.Map(); } - if (hasWeakMap && hasMap && hasForEach) return; + if (hasWeakMap && hasMap && hasForEach) { return; } var namespaces = Object.create(null); var count = 0; @@ -43,7 +41,9 @@ if ((this === obj) && (n in namespaces) && (namespaces[n] === namespace)) { - if (!(n in privates)) privates[n] = Object.create(null); + if (!(n in privates)) { + privates[n] = Object.create(null); + } return privates[n]; } else { @@ -62,9 +62,13 @@ var n = count++; namespaces[n] = namespace; var map = function (key) { - if (key !== Object(key)) throw new Error('value is not a non-null object'); + if (key !== Object(key)) { + throw new Error('value is not a non-null object'); + } var privates = key.valueOf(namespace, n); - if (privates !== key.valueOf()) return privates; + if (privates !== key.valueOf()) { + return privates; + } reDefineValueOf(key); return key.valueOf(namespace, n); }; @@ -114,9 +118,9 @@ var nullMap = Object.create(null); namespaces[n] = namespace; var map = function (key) { - if (key === null) return nullMap; + if (key === null) { return nullMap; } var privates = key.valueOf(namespace, n); - if (privates !== key.valueOf()) return privates; + if (privates !== key.valueOf()) { return privates; } reDefineValueOf(key); return key.valueOf(namespace, n); }; @@ -201,7 +205,7 @@ clear: { value: function () { keys.length = 0; - for (var key in map) map[key].clear(); + for (var key in map) { map[key].clear(); } size = 0; } }, @@ -293,4 +297,4 @@ return m; }; } -})(); \ No newline at end of file +})(); diff --git a/lib/common/Helper.js b/lib/common/Helper.js index 56ed74e..2126608 100644 --- a/lib/common/Helper.js +++ b/lib/common/Helper.js @@ -13,13 +13,11 @@ * * * Hprose Helper for Node.js. * * * - * LastModified: Mar 2, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ (function() { 'use strict'; diff --git a/lib/common/Polyfill.js b/lib/common/Polyfill.js new file mode 100644 index 0000000..a636bbf --- /dev/null +++ b/lib/common/Polyfill.js @@ -0,0 +1,413 @@ +/**********************************************************\ +| | +| hprose | +| | +| Official WebSite: http://www.hprose.com/ | +| http://www.hprose.org/ | +| | +\**********************************************************/ + +/**********************************************************\ + * * + * Polyfill.js * + * * + * Polyfill for Node.js. * + * * + * LastModified: Mar 3, 2016 * + * Author: Ma Bingyao * + * * +\**********************************************************/ + +'use strict'; +/* Function */ +if (!Function.prototype.bind) { + Object.defineProperty(Function.prototype, 'bind', { value: function(oThis) { + if (typeof this !== 'function') { + throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); + } + var aArgs = Array.prototype.slice.call(arguments, 1), + toBind = this, + NOP = function() {}, + bound = function() { + return toBind.apply(this instanceof NOP ? this : oThis, + aArgs.concat(Array.prototype.slice.call(arguments))); + }; + if (this.prototype) { + NOP.prototype = this.prototype; + } + bound.prototype = new NOP(); + return bound; + } }); +} +/* Array */ +if (!Array.prototype.includes) { + Object.defineProperty(Array.prototype, 'includes', { value: function(searchElement /*, fromIndex*/ ) { + var O = Object(this); + var len = parseInt(O.length, 10) || 0; + if (len === 0) { + return false; + } + var n = parseInt(arguments[1], 10) || 0; + var k; + if (n >= 0) { + k = n; + } + else { + k = len + n; + if (k < 0) { k = 0; } + } + var currentElement; + while (k < len) { + currentElement = O[k]; + if (searchElement === currentElement || + (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN + return true; + } + k++; + } + return false; + } }); +} +if (!Array.prototype.find) { + Object.defineProperty(Array.prototype, 'find', { value: function(predicate) { + if (this === null || this === undefined) { + throw new TypeError('Array.prototype.find called on null or undefined'); + } + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + var list = Object(this); + var length = list.length >>> 0; + var thisArg = arguments[1]; + var value; + for (var i = 0; i < length; i++) { + value = list[i]; + if (predicate.call(thisArg, value, i, list)) { + return value; + } + } + return undefined; + } }); +} +if (!Array.prototype.findIndex) { + Object.defineProperty(Array.prototype, 'findIndex', { value: function(predicate) { + if (this === null || this === undefined) { + throw new TypeError('Array.prototype.findIndex called on null or undefined'); + } + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } + var list = Object(this); + var length = list.length >>> 0; + var thisArg = arguments[1]; + var value; + + for (var i = 0; i < length; i++) { + value = list[i]; + if (predicate.call(thisArg, value, i, list)) { + return i; + } + } + return -1; + } }); +} +if (!Array.prototype.fill) { + Object.defineProperty(Array.prototype, 'fill', { value: function(value) { + if (this === null || this === undefined) { + throw new TypeError('this is null or not defined'); + } + var O = Object(this); + var len = O.length >>> 0; + var start = arguments[1]; + var relativeStart = start >> 0; + var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); + var end = arguments[2]; + var relativeEnd = end === undefined ? len : end >> 0; + var f = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); + + while (k < f) { + O[k] = value; + k++; + } + return O; + } }); +} +if (!Array.prototype.copyWithin) { + Object.defineProperty(Array.prototype, 'copyWithin', { value: function(target, start/*, end*/) { + if (this === null || this === undefined) { + throw new TypeError('this is null or not defined'); + } + var O = Object(this); + var len = O.length >>> 0; + var relativeTarget = target >> 0; + var to = relativeTarget < 0 ? Math.max(len + relativeTarget, 0) : Math.min(relativeTarget, len); + var relativeStart = start >> 0; + var from = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); + var end = arguments[2]; + var relativeEnd = end === undefined ? len : end >> 0; + var f = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); + var count = Math.min(f - from, len - to); + var direction = 1; + if (from < to && to < (from + count)) { + direction = -1; + from += count - 1; + to += count - 1; + } + while (count > 0) { + if (from in O) { + O[to] = O[from]; + } + else { + delete O[to]; + } + from += direction; + to += direction; + count--; + } + return O; + } }); +} +if (!Array.from) { + Object.defineProperty(Array, 'from', { value: (function() { + var toStr = Object.prototype.toString; + var isCallable = function(fn) { + return typeof fn === 'function' || toStr.call(fn) === '[object Function]'; + }; + var toInteger = function(value) { + var number = Number(value); + if (isNaN(number)) { return 0; } + if (number === 0 || !isFinite(number)) { return number; } + return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); + }; + var maxSafeInteger = Math.pow(2, 53) - 1; + var toLength = function(value) { + var len = toInteger(value); + return Math.min(Math.max(len, 0), maxSafeInteger); + }; + + return function(arrayLike/*, mapFn, thisArg */) { + var C = this; + var items = Object(arrayLike); + if (arrayLike === null || arrayLike === undefined) { + throw new TypeError("Array.from requires an array-like object - not null or undefined"); + } + var mapFn = arguments.length > 1 ? arguments[1] : void undefined; + var T; + if (typeof mapFn !== 'undefined') { + if (!isCallable(mapFn)) { + throw new TypeError('Array.from: when provided, the second argument must be a function'); + } + if (arguments.length > 2) { + T = arguments[2]; + } + } + var len = toLength(items.length); + var A = isCallable(C) ? Object(new C(len)) : new Array(len); + var k = 0; + var kValue; + while (k < len) { + kValue = items[k]; + if (mapFn) { + A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k); + } + else { + A[k] = kValue; + } + k += 1; + } + A.length = len; + return A; + }; + }()) }); +} +if (!Array.of) { + Object.defineProperty(Array, 'of', { value: function() { + return Array.prototype.slice.call(arguments); + } }); +} +/* String */ +if (!String.prototype.startsWith) { + Object.defineProperty(String.prototype, 'startsWith', { value: function(searchString, position){ + position = position || 0; + return this.substr(position, searchString.length) === searchString; + } }); +} +if (!String.prototype.endsWith) { + Object.defineProperty(String.prototype, 'endsWith', { value: function(searchString, position) { + var subjectString = this.toString(); + if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { + position = subjectString.length; + } + position -= searchString.length; + var lastIndex = subjectString.indexOf(searchString, position); + return lastIndex !== -1 && lastIndex === position; + } }); +} +if (!String.prototype.includes) { + Object.defineProperty(String.prototype, 'includes', { value: function() { + if (typeof arguments[1] === "number") { + if (this.length < arguments[0].length + arguments[1].length) { + return false; + } + else { + return this.substr(arguments[1], arguments[0].length) === arguments[0]; + } + } + else { + return String.prototype.indexOf.apply(this, arguments) !== -1; + } + } }); +} +if (!String.prototype.repeat) { + Object.defineProperty(String.prototype, 'repeat', { value: function(count) { + var str = this.toString(); + count = +count; + if (count !== count) { + count = 0; + } + if (count < 0) { + throw new RangeError('repeat count must be non-negative'); + } + if (count === Infinity) { + throw new RangeError('repeat count must be less than infinity'); + } + count = Math.floor(count); + if (str.length === 0 || count === 0) { + return ''; + } + // Ensuring count is a 31-bit integer allows us to heavily optimize the + // main part. But anyway, most current (August 2014) browsers can't handle + // strings 1 << 28 chars or longer, so: + if (str.length * count >= 1 << 28) { + throw new RangeError('repeat count must not overflow maximum string size'); + } + var rpt = ''; + for (;;) { + if ((count & 1) === 1) { + rpt += str; + } + count >>>= 1; + if (count === 0) { + break; + } + str += str; + } + // Could we try: + // return Array(count + 1).join(this); + return rpt; + } }); +} +if (!String.prototype.trim) { + Object.defineProperty(String.prototype, 'trim', { value: function() { + return this.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, ''); + } }); +} +if (!String.prototype.trimLeft) { + Object.defineProperty(String.prototype, 'trimLeft', { value: function() { + return this.toString().replace(/^[\s\xa0]+/, ''); + } }); +} +if (!String.prototype.trimRight) { + Object.defineProperty(String.prototype, 'trimRight', { value: function() { + return this.toString().replace(/[\s\xa0]+$/, ''); + } }); +} +/* Object */ +if (!Object.keys) { + Object.defineProperty(Object, 'keys', { value: (function () { + var hasOwnProperty = Object.prototype.hasOwnProperty, + hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), + dontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ], + dontEnumsLength = dontEnums.length; + return function (obj) { + if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) { + throw new TypeError('Object.keys called on non-object'); + } + var result = []; + for (var prop in obj) { + if (hasOwnProperty.call(obj, prop)) { + result.push(prop); + } + } + if (hasDontEnumBug) { + for (var i=0; i < dontEnumsLength; i++) { + if (hasOwnProperty.call(obj, dontEnums[i])) { + result.push(dontEnums[i]); + } + } + } + return result; + }; + })() }); +} +/* Generic methods */ +var generic = global.hprose.generic; + +function genericMethods(obj, properties) { + var proto = obj.prototype; + for (var i = 0, len = properties.length; i < len; i++) { + var property = properties[i]; + var method = proto[property]; + if (typeof method === 'function' && typeof obj[property] === 'undefined') { + Object.defineProperty(obj, property, { value: generic(method) }); + } + } +} +genericMethods(Array, [ + "pop", + "push", + "reverse", + "shift", + "sort", + "splice", + "unshift", + "concat", + "join", + "slice", + "indexOf", + "lastIndexOf", + "filter", + "forEach", + "every", + "map", + "some", + "reduce", + "reduceRight", + "includes", + "find", + "findIndex" +]); +genericMethods(String, [ + 'quote', + 'substring', + 'toLowerCase', + 'toUpperCase', + 'charAt', + 'charCodeAt', + 'indexOf', + 'lastIndexOf', + 'include', + 'startsWith', + 'endsWith', + 'repeat', + 'trim', + 'trimLeft', + 'trimRight', + 'toLocaleLowerCase', + 'toLocaleUpperCase', + 'match', + 'search', + 'replace', + 'split', + 'substr', + 'concat', + 'slice' +]); diff --git a/lib/common/ResultMode.js b/lib/common/ResultMode.js index 6979401..1e49aa9 100644 --- a/lib/common/ResultMode.js +++ b/lib/common/ResultMode.js @@ -13,13 +13,11 @@ * * * Hprose ResultMode for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; global.hprose.ResultMode = { diff --git a/lib/common/setImmediate.js b/lib/common/setImmediate.js index d0ae905..9a2d668 100644 --- a/lib/common/setImmediate.js +++ b/lib/common/setImmediate.js @@ -13,17 +13,15 @@ * * * setImmediate for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ (function() { 'use strict'; - if (global.setImmediate) return; + if (global.setImmediate) { return; } var slice = Function.prototype.call.bind(Array.prototype.slice); var nextId = 1; diff --git a/lib/filter/JSONRPCClientFilter.js b/lib/filter/JSONRPCClientFilter.js index 12ae7e0..79d9ca4 100644 --- a/lib/filter/JSONRPCClientFilter.js +++ b/lib/filter/JSONRPCClientFilter.js @@ -13,19 +13,18 @@ * * * jsonrpc client filter for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var Tags = global.hprose.Tags; var BytesIO = global.hprose.BytesIO; var Writer = global.hprose.Writer; var Reader = global.hprose.Reader; +var JSON = global.JSON; var s_id = 1; @@ -33,7 +32,7 @@ function JSONRPCClientFilter(version) { this.version = version || '2.0'; } -JSONRPCClientFilter.prototype.inputFilter = function inputFilter(data, context) { +JSONRPCClientFilter.prototype.inputFilter = function inputFilter(data/*, context*/) { var json = BytesIO.toString(data); if (json.charAt(0) === '{') { json = '[' + json + ']'; @@ -56,7 +55,7 @@ JSONRPCClientFilter.prototype.inputFilter = function inputFilter(data, context) return stream.bytes; }; -JSONRPCClientFilter.prototype.outputFilter = function outputFilter(data, context) { +JSONRPCClientFilter.prototype.outputFilter = function outputFilter(data/*, context*/) { var requests = []; var stream = new BytesIO(data); var reader = new Reader(stream, false, false); diff --git a/lib/filter/JSONRPCServiceFilter.js b/lib/filter/JSONRPCServiceFilter.js index 309c0ea..02e6148 100644 --- a/lib/filter/JSONRPCServiceFilter.js +++ b/lib/filter/JSONRPCServiceFilter.js @@ -13,19 +13,18 @@ * * * jsonrpc service filter for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var Tags = global.hprose.Tags; var BytesIO = global.hprose.BytesIO; var Writer = global.hprose.Writer; var Reader = global.hprose.Reader; +var JSON = global.JSON; var leftbrace = 0x7B; // '{' var leftbracket = 0x5B; // '[' diff --git a/lib/hprose.js b/lib/hprose.js index 3b60192..24adf9c 100644 --- a/lib/hprose.js +++ b/lib/hprose.js @@ -13,18 +13,17 @@ * * * hprose for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; global.hprose = global.hprose || Object.create(null); require('./common/Helper.js'); +require('./common/Polyfill.js'); require('./common/HarmonyMaps.js'); require('./common/setImmediate.js'); require('./common/Future.js'); diff --git a/lib/io/BytesIO.js b/lib/io/BytesIO.js index 939adba..80ead95 100644 --- a/lib/io/BytesIO.js +++ b/lib/io/BytesIO.js @@ -13,20 +13,17 @@ * * * Hprose BytesIO for Node.js. * * * - * LastModified: Mar 2, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var toBinaryString = global.hprose.toBinaryString; var _EMPTY_BYTES = new Uint8Array(0); var _INIT_SIZE = 1024; -var indexof = Function.prototype.call.bind(Array.prototype.indexOf); function writeInt32BE(bytes, p, i) { bytes[p++] = i >>> 24 & 0xFF; @@ -215,16 +212,16 @@ function readLongString(bytes, n) { } function readString(bytes, n) { - if (n === undefined || n === null || (n < 0)) n = bytes.length; - if (n === 0) return ['', 0]; + if (n === undefined || n === null || (n < 0)) { n = bytes.length; } + if (n === 0) { return ['', 0]; } return ((n < 100000) ? readShortString(bytes, n) : readLongString(bytes, n)); } function readStringAsBytes(bytes, n) { - if (n === undefined) n = bytes.length; - if (n === 0) return [_EMPTY_BYTES, 0]; + if (n === undefined) { n = bytes.length; } + if (n === 0) { return [_EMPTY_BYTES, 0]; } var i = 0, off = 0; for (var len = bytes.length; i < n && off < len; i++) { var unit = bytes[off++]; @@ -413,7 +410,7 @@ Object.defineProperties(BytesIO.prototype, { } }, write: { value: function(data) { var n = data.byteLength || data.length; - if (n === 0) return; + if (n === 0) { return; } this._grow(n); var bytes = this._bytes; var length = this._length; @@ -437,7 +434,7 @@ Object.defineProperties(BytesIO.prototype, { } }, writeAsciiString: { value: function(str) { var n = str.length; - if (n === 0) return; + if (n === 0) { return; } this._grow(n); var bytes = this._bytes; var l = this._length; @@ -448,7 +445,7 @@ Object.defineProperties(BytesIO.prototype, { } }, writeString: { value: function(str) { var n = str.length; - if (n === 0) return; + if (n === 0) { return; } // A single code unit uses at most 3 bytes. // Two code units at most 4. this._grow(n * 3); @@ -504,7 +501,7 @@ Object.defineProperties(BytesIO.prototype, { if (this._off + n > this._length) { n = this._length - this._off; } - if (n === 0) return _EMPTY_BYTES; + if (n === 0) { return _EMPTY_BYTES; } return this._bytes.subarray(this._off, this._off += n); } }, skip: { value: function(n) { @@ -519,7 +516,7 @@ Object.defineProperties(BytesIO.prototype, { } }, // the result is an Uint8Array, and includes tag. readBytes: { value: function(tag) { - var pos = indexof(this._bytes, tag, this._off); + var pos = Array.indexOf(this._bytes, tag, this._off); var buf; if (pos === -1) { buf = this._bytes.subarray(this._off, this._length); @@ -534,7 +531,7 @@ Object.defineProperties(BytesIO.prototype, { // the result is a String, and doesn't include tag. // but the position is the same as readBytes readUntil: { value: function(tag) { - var pos = indexof(this._bytes, tag, this._off); + var pos = Array.indexOf(this._bytes, tag, this._off); var str = ''; if (pos === this._off) { this._off++; @@ -553,7 +550,7 @@ Object.defineProperties(BytesIO.prototype, { if (this._off + n > this._length) { n = this._length - this._off; } - if (n === 0) return ''; + if (n === 0) { return ''; } return toBinaryString(this._bytes.subarray(this._off, this._off += n)); } }, // n is the UTF16 length @@ -605,7 +602,7 @@ Object.defineProperties(BytesIO.prototype, { function toString(data) { /* jshint -W086 */ - if (data.length === 0) return ''; + if (data.length === 0) { return ''; } switch(data.constructor) { case String: return data; case Buffer: return data.toString(); @@ -632,4 +629,4 @@ Object.defineProperties(BytesIO, { toBuffer: { value: toBuffer } }); -global.hprose.BytesIO = BytesIO; \ No newline at end of file +global.hprose.BytesIO = BytesIO; diff --git a/lib/io/ClassManager.js b/lib/io/ClassManager.js index 67fa6cd..a237588 100644 --- a/lib/io/ClassManager.js +++ b/lib/io/ClassManager.js @@ -13,13 +13,11 @@ * * * hprose ClassManager for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var WeakMap = global.WeakMap; diff --git a/lib/io/Formatter.js b/lib/io/Formatter.js index ef12aee..00fb11a 100644 --- a/lib/io/Formatter.js +++ b/lib/io/Formatter.js @@ -13,13 +13,11 @@ * * * Hprose Formatter for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var BytesIO = global.hprose.BytesIO; diff --git a/lib/io/Reader.js b/lib/io/Reader.js index 9c190ff..9755aff 100644 --- a/lib/io/Reader.js +++ b/lib/io/Reader.js @@ -13,13 +13,11 @@ * * * Hprose Reader for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var Map = global.Map; @@ -656,12 +654,12 @@ Reader.prototype.constructor = Reader; Object.defineProperties(Reader.prototype, { useHarmonyMap: { value: false, writable: true }, checkTag: { value: function(expectTag, tag) { - if (tag === undefined) tag = this.stream.readByte(); - if (tag !== expectTag) unexpectedTag(tag, expectTag); + if (tag === undefined) { tag = this.stream.readByte(); } + if (tag !== expectTag) { unexpectedTag(tag, expectTag); } } }, checkTags: { value: function(expectTags, tag) { - if (tag === undefined) tag = this.stream.readByte(); - if (expectTags.indexOf(tag) >= 0) return tag; + if (tag === undefined) { tag = this.stream.readByte(); } + if (expectTags.indexOf(tag) >= 0) { return tag; } unexpectedTag(tag, expectTags); } }, unserialize: { value: function() { diff --git a/lib/io/Tags.js b/lib/io/Tags.js index 3ca3a2b..73ff467 100644 --- a/lib/io/Tags.js +++ b/lib/io/Tags.js @@ -13,13 +13,11 @@ * * * Hprose Tags for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; global.hprose.Tags = { diff --git a/lib/io/Writer.js b/lib/io/Writer.js index 3e004d6..c92b3bf 100644 --- a/lib/io/Writer.js +++ b/lib/io/Writer.js @@ -13,13 +13,11 @@ * * * Hprose Writer for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var Map = global.Map; @@ -30,7 +28,7 @@ var ClassManager = global.hprose.ClassManager; function getClassName(obj) { var cls = obj.constructor; var classname = ClassManager.getClassAlias(cls); - if (classname) return classname; + if (classname) { return classname; } if (cls.name) { classname = cls.name; } @@ -310,9 +308,14 @@ function writeBytes(writer, bytes) { var stream = writer.stream; stream.writeByte(Tags.TagBytes); var n = bytes.byteLength || bytes.length; - if (n > 0) stream.writeAsciiString('' + n); - stream.writeByte(Tags.TagQuote); - if (n > 0) stream.write(bytes); + if (n > 0) { + stream.writeAsciiString('' + n); + stream.writeByte(Tags.TagQuote); + stream.write(bytes); + } + else { + stream.writeByte(Tags.TagQuote); + } stream.writeByte(Tags.TagQuote); } @@ -321,9 +324,14 @@ function writeString(writer, str) { var stream = writer.stream; var n = str.length; stream.writeByte(Tags.TagString); - if (n > 0) stream.writeAsciiString('' + n); - stream.writeByte(Tags.TagQuote); - if (n > 0) stream.writeString(str); + if (n > 0) { + stream.writeAsciiString('' + n); + stream.writeByte(Tags.TagQuote); + stream.writeString(str); + } + else { + stream.writeByte(Tags.TagQuote); + } stream.writeByte(Tags.TagQuote); } @@ -332,10 +340,15 @@ function writeArray(writer, array, writeElem) { var stream = writer.stream; var n = array.length; stream.writeByte(Tags.TagList); - if (n > 0) stream.writeAsciiString('' + n); - stream.writeByte(Tags.TagOpenbrace); - for (var i = 0; i < n; i++) { - writeElem(writer, array[i]); + if (n > 0) { + stream.writeAsciiString('' + n); + stream.writeByte(Tags.TagOpenbrace); + for (var i = 0; i < n; i++) { + writeElem(writer, array[i]); + } + } + else { + stream.writeByte(Tags.TagOpenbrace); } stream.writeByte(Tags.TagClosebrace); } @@ -364,11 +377,16 @@ function writeMap(writer, map) { } var n = fields.length; stream.writeByte(Tags.TagMap); - if (n > 0) stream.writeAsciiString('' + n); - stream.writeByte(Tags.TagOpenbrace); - for (var i = 0; i < n; i++) { - serialize(writer, fields[i]); - serialize(writer, map[fields[i]]); + if (n > 0) { + stream.writeAsciiString('' + n); + stream.writeByte(Tags.TagOpenbrace); + for (var i = 0; i < n; i++) { + serialize(writer, fields[i]); + serialize(writer, map[fields[i]]); + } + } + else { + stream.writeByte(Tags.TagOpenbrace); } stream.writeByte(Tags.TagClosebrace); } @@ -378,12 +396,17 @@ function writeHarmonyMap(writer, map) { var stream = writer.stream; var n = map.size; stream.writeByte(Tags.TagMap); - if (n > 0) stream.writeAsciiString('' + n); - stream.writeByte(Tags.TagOpenbrace); - map.forEach(function(value, key) { - serialize(writer, key); - serialize(writer, value); - }); + if (n > 0) { + stream.writeAsciiString('' + n); + stream.writeByte(Tags.TagOpenbrace); + map.forEach(function(value, key) { + serialize(writer, key); + serialize(writer, value); + }); + } + else { + stream.writeByte(Tags.TagOpenbrace); + } stream.writeByte(Tags.TagClosebrace); } @@ -424,10 +447,15 @@ function writeClass(writer, classname, fields) { stream.writeByte(Tags.TagQuote); stream.writeString(classname); stream.writeByte(Tags.TagQuote); - if (n > 0) stream.writeAsciiString('' + n); - stream.writeByte(Tags.TagOpenbrace); - for (var i = 0; i < n; i++) { - writeString(writer, fields[i]); + if (n > 0) { + stream.writeAsciiString('' + n); + stream.writeByte(Tags.TagOpenbrace); + for (var i = 0; i < n; i++) { + writeString(writer, fields[i]); + } + } + else { + stream.writeByte(Tags.TagOpenbrace); } stream.writeByte(Tags.TagClosebrace); var index = writer._fieldsref.length; diff --git a/lib/server/HttpServer.js b/lib/server/HttpServer.js index 72f9db7..fd030d4 100644 --- a/lib/server/HttpServer.js +++ b/lib/server/HttpServer.js @@ -13,13 +13,11 @@ * * * Hprose Http Server for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); diff --git a/lib/server/HttpService.js b/lib/server/HttpService.js index 46ccc3f..5ccff92 100644 --- a/lib/server/HttpService.js +++ b/lib/server/HttpService.js @@ -13,13 +13,11 @@ * * * Hprose Http Service for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var fs = require('fs'); @@ -179,7 +177,7 @@ function HttpService() { function setCrossDomainXmlContent(value) { _crossDomainXmlFile = null; - if (typeof(value) === 'string') value = new Buffer(value); + if (typeof(value) === 'string') { value = new Buffer(value); } _crossDomainXmlContent = value; } @@ -198,7 +196,7 @@ function HttpService() { function setClientAccessPolicyXmlContent(value) { _clientAccessPolicyXmlFile = null; - if (typeof(value) === 'string') value = new Buffer(value); + if (typeof(value) === 'string') { value = new Buffer(value); } _clientAccessPolicyXmlContent = value; } @@ -229,8 +227,8 @@ function HttpService() { var bytes = new BytesIO(); request.on('data', function(data) { bytes.write(data); }); request.on('end', function() { - if (_clientAccessPolicyXmlContent !== null && clientAccessPolicyXmlHandler(request, response)) return; - if (_crossDomainXmlContent !== null && crossDomainXmlHandler(request, response)) return; + if (_clientAccessPolicyXmlContent !== null && clientAccessPolicyXmlHandler(request, response)) { return; } + if (_crossDomainXmlContent !== null && crossDomainXmlHandler(request, response)) { return; } try { sendHeader(context); } @@ -253,11 +251,11 @@ function HttpService() { onSendHeader: { get: getSendHeader, set: setSendHeader }, crossDomain: { get: isCrossDomainEnabled, set: setCrossDomainEnabled }, p3p: { get: isP3PEnabled, set: setP3PEnabled }, - get: { get: isGetEnabled, set: isGetEnabled }, + get: { get: isGetEnabled, set: setGetEnabled }, crossDomainXmlFile: { get: getCrossDomainXmlFile, set: setCrossDomainXmlFile }, crossDomainXmlContent: { get: getCrossDomainXmlContent, set: setCrossDomainXmlContent }, - clientAccessPolicyXmlFile: { get: getClientAccessPolicyXmlFile, set: getClientAccessPolicyXmlFile }, - clientAccessPolicyXmlContent: { get: getClientAccessPolicyXmlContent, set: getClientAccessPolicyXmlContent }, + clientAccessPolicyXmlFile: { get: getClientAccessPolicyXmlFile, set: setClientAccessPolicyXmlFile }, + clientAccessPolicyXmlContent: { get: getClientAccessPolicyXmlContent, set: setClientAccessPolicyXmlContent }, addAccessControlAllowOrigin: { value: addAccessControlAllowOrigin }, removeAccessControlAllowOrigin: { value: removeAccessControlAllowOrigin }, handle: { value: handle } diff --git a/lib/server/Server.js b/lib/server/Server.js index dee5c7d..9657554 100644 --- a/lib/server/Server.js +++ b/lib/server/Server.js @@ -13,13 +13,11 @@ * * * Hprose Server for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var parse = require('url').parse; @@ -34,7 +32,7 @@ function create(uri, tlsOptions) { var port; if (protocol === 'http:' || protocol === 'https:') { - port = parseInt(parser.port); + port = parseInt(parser.port, 10); if (!port) { port = (protocol === 'http:' ? 80 : 443); } @@ -51,7 +49,7 @@ function create(uri, tlsOptions) { options.host = parser.hostname; } if (parser.port) { - options.port = parseInt(parser.port); + options.port = parseInt(parser.port, 10); } return new SocketServer(options, tlsOptions); } @@ -61,7 +59,7 @@ function create(uri, tlsOptions) { } if (protocol === 'ws:' || protocol === 'wss:') { - port = parseInt(parser.port); + port = parseInt(parser.port, 10); if (!port) { port = (protocol === 'http:' ? 80 : 443); } diff --git a/lib/server/Service.js b/lib/server/Service.js index 0761c2c..11cda15 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,13 +13,11 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); @@ -53,7 +51,7 @@ function getFuncName(func, obj) { var funcname = f.substr(0, f.indexOf('(')).replace(/(^\s*function\s*)|(\s*$)/ig, ''); if ((funcname === '') && obj) { for (var name in obj) { - if (obj[name] === func) return name; + if (obj[name] === func) { return name; } } } return funcname; @@ -177,19 +175,19 @@ function Service() { self.emit('beforeInvoke', name, args, context.byref, context); if (_onBeforeInvoke !== null) { var value = _onBeforeInvoke(name, args, context.byref, context); - if (isError(value)) throw value; + if (isError(value)) { throw value; } if (Future.isPromise(value)) { return value.then(function(e) { - if (isError(e)) throw e; + if (isError(e)) { throw e; } return invoke(name, args, context); - }).catch(function(e) { + }).then(null, function(e) { return sendError(e, context); }); } } var result = invoke(name, args, context); if (Future.isPromise(result)) { - return result.catch(function(e) { + return result.then(null, function(e) { return sendError(e, context); }); } @@ -210,7 +208,7 @@ function Service() { } if (context.async) { return Future.promise(function(resolve, reject) { - if (passContext) args.push(context); + if (passContext) { args.push(context); } args.push(function(result) { if (isError(result)) { reject(result); @@ -223,7 +221,7 @@ function Service() { }); } else { - if (passContext) args.push(context); + if (passContext) { args.push(context); } return callService(args, context); } } @@ -232,7 +230,7 @@ function Service() { var result = _invokeHandler(name, args, context); if (Future.isPromise(result)) { return result.then(function(result) { - if (isError(result)) throw result; + if (isError(result)) { throw result; } return afterInvoke(name, args, context, result); }); } @@ -250,10 +248,10 @@ function Service() { self.emit('afterInvoke', name, args, context.byref, result, context); if (_onAfterInvoke !== null) { var value = _onAfterInvoke(name, args, context.byref, result, context); - if (isError(value)) throw value; + if (isError(value)) { throw value; } if (Future.isPromise(value)) { return value.then(function(e) { - if (isError(e)) throw e; + if (isError(e)) { throw e; } return doOutput(args, context, result); }); } @@ -298,10 +296,10 @@ function Service() { var alias = name.toLowerCase(); var cc = {}; var key; - for (key in context) cc[key] = context[key]; + for (key in context) { cc[key] = context[key]; } var call = _calls[alias] || _calls['*']; if (call) { - for (key in call) cc[key] = call[key]; + for (key in call) { cc[key] = call[key]; } } var args = []; cc.byref = false; @@ -337,7 +335,7 @@ function Service() { }); } - function doFunctionList(context) { + function doFunctionList() { var stream = new BytesIO(); var writer = new Writer(stream, true); stream.writeByte(Tags.TagFunctions); @@ -1113,6 +1111,7 @@ function Service() { debug: { get: isDebugEnabled, set: setDebugEnabled }, simple: { get: getSimpleMode, set: setSimpleMode }, passContext: { get: getPassContext, set: setPassContext }, + errorDelay: { get: getErrorDelay, set: setErrorDelay }, filter: { get: getFilter, set: setFilter }, addFilter: { value: addFilter }, removeFilter: { value: removeFilter }, diff --git a/lib/server/SocketServer.js b/lib/server/SocketServer.js index e620654..41d638e 100644 --- a/lib/server/SocketServer.js +++ b/lib/server/SocketServer.js @@ -13,13 +13,11 @@ * * * Hprose Socket Server for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); diff --git a/lib/server/SocketService.js b/lib/server/SocketService.js index 9466011..38d375a 100644 --- a/lib/server/SocketService.js +++ b/lib/server/SocketService.js @@ -13,22 +13,21 @@ * * * Hprose Socket Service for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); -var setImmediate = global.setImmediate; var Service = global.hprose.Service; var BytesIO = global.hprose.BytesIO; var Future = global.hprose.Future; +function noop() {} + function SocketService() { Service.call(this); @@ -140,7 +139,7 @@ function SocketService() { }; try { self.emit('accept', context); - if (_onAccept) _onAccept(context); + if (_onAccept) { _onAccept(context); } } catch(e) { socket.end(); @@ -149,11 +148,11 @@ function SocketService() { socket.on('close', function() { try { self.emit('close', context); - if (_onClose) _onClose(context); + if (_onClose) { _onClose(context); } } catch(e) {} }); - socket.on('end', function(e) { }); + socket.on('end', noop); socket.on('error', function(e) { try { self.emit('sendError', e, context); diff --git a/lib/server/WebSocketServer.js b/lib/server/WebSocketServer.js index d2ebcb0..8d071da 100644 --- a/lib/server/WebSocketServer.js +++ b/lib/server/WebSocketServer.js @@ -13,13 +13,11 @@ * * * Hprose WebSocket Server for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); @@ -48,7 +46,7 @@ function WebSocketServer(options, tlsOptions) { server: self.server, userdata:{} }; - if (socket) context.socket = socket; + if (socket) { context.socket = socket; } try { self.emit('sendError', e, context); if (self.onSendError) { diff --git a/lib/server/WebSocketService.js b/lib/server/WebSocketService.js index c30f2c6..8f5db49 100644 --- a/lib/server/WebSocketService.js +++ b/lib/server/WebSocketService.js @@ -13,13 +13,11 @@ * * * Hprose WebSocket Service for Node.js. * * * - * LastModified: Feb 25, 2016 * + * LastModified: Mar 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ -/*global global */ -/*jshint node:true, noused:true, eqeqeq:true */ 'use strict'; var util = require('util'); @@ -102,7 +100,7 @@ function WebSocketService() { }; try { self.emit('accept', context); - if (_onAccept) _onAccept(context); + if (_onAccept) { _onAccept(context); } } catch(e) { ws.close(); @@ -111,7 +109,7 @@ function WebSocketService() { ws.on('close', function() { try { self.emit('close',context); - if (_onClose) _onClose(context); + if (_onClose) { _onClose(context); } } catch(e) {} }); diff --git a/package.json b/package.json index e6083f9..ec0cad4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.9", + "version": "2.0.10", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 30dd59b5a5b98436f44d2b1532a7dda4a1eb4d4e Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 4 Mar 2016 15:07:09 +0800 Subject: [PATCH 020/131] Fixed issue #7 --- example/timeclient.js | 2 +- example/timeserver.js | 21 +++++++++++++++++++-- lib/server/Service.js | 38 ++++++++++++++++++++------------------ 3 files changed, 40 insertions(+), 21 deletions(-) diff --git a/example/timeclient.js b/example/timeclient.js index 85dd394..ba193b3 100644 --- a/example/timeclient.js +++ b/example/timeclient.js @@ -2,7 +2,7 @@ 'use strict'; var hprose = require('hprose'); -var client = hprose.Client.create("http://0.0.0.0:8080/"); +var client = hprose.Client.create("http://127.0.0.1:8080/"); var count = 0; client.subscribe('time', function(date) { if (++count > 10) { diff --git a/example/timeserver.js b/example/timeserver.js index c8d49f0..b24264b 100644 --- a/example/timeserver.js +++ b/example/timeserver.js @@ -1,13 +1,30 @@ /*jshint node:true, eqeqeq:true */ 'use strict'; -var hprose = require('hprose'); +var hprose = require('../lib/hprose'); var server = hprose.Server.create("http://0.0.0.0:8080/"); server.publish('time'); + +function ClientListFilter() { + this.inputFilter = function(value) { + return value; + }; + this.outputFilter = function(value, context) { + console.log(context.clients.idlist('time')); + return value; + }; +} + +server.filter = new ClientListFilter(); + setInterval(function() { server.push('time', new Date()); }, 1000); + process.on('SIGINT', function() { - server.stop(); + console.log("server is stoping!"); + server.stop(); + process.exit(); }); + server.start(); diff --git a/lib/server/Service.js b/lib/server/Service.js index 11cda15..b57d1ee 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -848,15 +848,19 @@ function Service() { throw new Error('Wrong arguments'); } + function getTopics(topic) { + if (!(topic in _topics)) { + throw new Error('topic "' + topic + '" is not published.'); + } + return _topics[topic]; + } function delTimer(topics, id) { if ('timer' in topics[id]) { global.clearTimeout(topics[id].timer); delete topics[id].timer; } } - - function offline(topic, id) { - var topics = getTopics(topic); + function offline(topics, topic, id) { delTimer(topics, id); var messages = topics[id].messages; delete topics[id]; @@ -870,12 +874,16 @@ function Service() { self.emit('unsubscribe', topic, id, self); } } - function resetTimer(topic, id) { - var topics = getTopics(topic); + function setTimer(topics, topic, id) { + if (!('timer' in topics[id])) { + topics[id].timer = global.setTimeout(function() { + offline(topics, topic, id); + }, topics[id].heartbeat); + } + } + function resetTimer(topics, topic, id) { delTimer(topics, id); - topics[id].timer = global.setTimeout(function() { - offline(topic, id); - }, topics[id].heartbeat); + setTimer(topics, topic, id); } function setRequestTimer(topic, id, request, timeout) { var topics = getTopics(topic); @@ -888,7 +896,7 @@ function Service() { topics[id].heartbeat ); if (topics[id].count < 0) { - offline(topic, id); + offline(topics, topic, id); } else { topics[id].count--; @@ -918,7 +926,7 @@ function Service() { _topics[topic] = {}; _events[topic] = events; addFunction(function(id) { - var topics = _topics[topic]; + var topics = getTopics(topic); if (id in topics) { if (topics[id].count < 0) { topics[id].count = 0; @@ -927,7 +935,7 @@ function Service() { if (messages.length > 0) { var message = messages.shift(); message.detector.resolve(true); - resetTimer(topic, id); + resetTimer(topics, topic, id); return message.result; } else { @@ -955,12 +963,6 @@ function Service() { return setRequestTimer(topic, id, request, timeout); }, topic); } - function getTopics(topic) { - if (!(topic in _topics)) { - throw new Error('topic "' + topic + '" is not published.'); - } - return _topics[topic]; - } function _push(topic, id, result) { var topics = getTopics(topic); if (!(id in topics)) { @@ -974,7 +976,7 @@ function Service() { else { var detector = new Future(); topics[id].messages.push({ detector: detector, result: result }); - resetTimer(topic, id); + setTimer(topics, topic, id); return detector; } } From a8880f453fb72a81c14dfc8a8e8cb4ded2986604 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 26 Mar 2016 23:47:36 +0800 Subject: [PATCH 021/131] Fixed then. --- lib/common/Future.js | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 9311811..531e72b 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Mar 2, 2016 * + * LastModified: Mar 26, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -482,12 +482,7 @@ if (onfulfill || onreject) { var next = new Future(); if (this._state === FULFILLED) { - if (onfulfill) { - _resolve(onfulfill, onreject, this, next, this._value); - } - else { - next.resolve(this._value); - } + _resolve(onfulfill, onreject, this, next, this._value); } else if (this._state === REJECTED) { if (onreject) { From 0a8e9713da4d92eac630080502ce159ebbca3e56 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 28 Mar 2016 13:36:33 +0800 Subject: [PATCH 022/131] Added Future.promise.done. --- lib/common/Future.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/common/Future.js b/lib/common/Future.js index 531e72b..86af8ca 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -503,6 +503,11 @@ } return this; } }, + done: { value: function(onfulfill, onreject) { + this.then(onfulfill, onreject).then(null, function(error) { + setImmediate(function() { throw error; }); + }); + } }, inspect: { value: function() { switch (this._state) { case PENDING: return { state: 'pending' }; From b060f90517c81f0ea61fc9801d52a7ac03a6e6ba Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 28 Mar 2016 15:36:17 +0800 Subject: [PATCH 023/131] Added Future.promise.fail, Future.promise.complete, Future.promise.always --- lib/common/Future.js | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 86af8ca..821bdb7 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Mar 26, 2016 * + * LastModified: Mar 28, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -532,6 +532,9 @@ 'catch': { value: function(onreject) { return this.then(null, onreject); } }, + fail: { value: function(onreject) { + this.done(null, onreject); + } }, whenComplete: { value: function(action) { return this.then( function(v) { @@ -548,6 +551,12 @@ } ); } }, + complete: { value: function(oncomplete) { + return this.then(oncomplete, oncomplete); + } }, + always: { value: function(oncomplete) { + this.done(oncomplete, oncomplete); + } }, timeout: { value: function(duration, reason) { var future = new Future(); var timeoutId = setTimeout(function() { From 74a8702146a76487aff6e54331faf520a125ffbb Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 1 Apr 2016 19:32:08 +0800 Subject: [PATCH 024/131] Fixed retry --- lib/client/Client.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index 5e18e62..307555b 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Apr 1, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -130,8 +130,8 @@ function Client(uri, functions, settings) { if (context.failswitch) { if (++_index >= _uris.length) { _index = 0; - _uri = _uris[_index]; } + _uri = _uris[_index]; } if (context.idempotent) { if (--context.retry >= 0) { From 289503177351dfd98062822726d1af863e03f6e0 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 6 Apr 2016 15:24:18 +0800 Subject: [PATCH 025/131] Update package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ec0cad4..4e9c9c7 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "lib": "lib/" }, "main": "lib/hprose.js", - "optionalDependencies": { "ws": "*" }, + "optionalDependencies": { "ws": "~1.0.1" }, "devDependencies": { "promises-aplus-tests": "*" }, From ff789355c1cab55e57c524bcfeabce89f6615b31 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 11 Apr 2016 16:02:57 +0800 Subject: [PATCH 026/131] Added toPromise and fill method for Future --- lib/common/Future.js | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 821bdb7..7a6c7ed 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -61,6 +61,10 @@ return isFuture(obj) || (hasPromise && (obj instanceof global.Promise) && (typeof (obj.then === 'function'))); } + function toPromise(obj) { + return (isPromise(obj) ? obj : value(obj)); + } + function delayed(duration, value) { var computation = (typeof value === 'function') ? value : @@ -120,8 +124,7 @@ if (count === 0) { return value(result); } var future = new Future(); foreach(array, function(element, index) { - var f = (isPromise(element) ? element : value(element)); - f.then(function(value) { + toPromise(element).then(function(value) { result[index] = value; if (--count === 0) { future.resolve(result); @@ -142,8 +145,7 @@ return array.then(function(array) { var future = new Future(); foreach(array, function(element) { - var f = (isPromise(element) ? element : value(element)); - f.then(future.resolve, future.reject); + toPromise(element).fill(future); }); return future; }); @@ -160,8 +162,7 @@ var reasons = new Array(n); var future = new Future(); foreach(array, function(element, index) { - var f = (isPromise(element) ? element : value(element)); - f.then(future.resolve, function(e) { + toPromise(element).then(future.resolve, function(e) { reasons[index] = e; if (--count === 0) { future.reject(reasons); @@ -181,7 +182,7 @@ if (count === 0) { return value(result); } var future = new Future(); foreach(array, function(element, index) { - var f = (isPromise(element) ? element : value(element)); + var f = toPromise(element); f.whenComplete(function() { result[index] = f.inspect(); if (--count === 0) { @@ -337,6 +338,7 @@ promise: { value: promise }, isFuture: { value: isFuture }, isPromise: { value: isPromise }, + toPromise: { value: toPromise }, join: { value: join }, any: { value: any }, settle: { value: settle }, @@ -557,13 +559,16 @@ always: { value: function(oncomplete) { this.done(oncomplete, oncomplete); } }, + fill: { value: function(future) { + this.then(future.resolve, future.reject); + } }, timeout: { value: function(duration, reason) { var future = new Future(); var timeoutId = setTimeout(function() { future.reject(reason || new TimeoutError('timeout')); }, duration); this.whenComplete(function() { clearTimeout(timeoutId); }) - .then(future.resolve, future.reject); + .fill(future); return future; } }, delay: { value: function(duration) { From 8a3032f77f9a42c1923c3b25048777abbe05b67b Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 11 Apr 2016 16:03:32 +0800 Subject: [PATCH 027/131] Change modified date --- lib/common/Future.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 7a6c7ed..1a23d25 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Mar 28, 2016 * + * LastModified: Apr 11, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ From 1ed9a86c9beb9b01bf60dccbefbe0cf5281af14f Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 21 Apr 2016 16:29:05 +0800 Subject: [PATCH 028/131] Update optionalDependencies --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 4e9c9c7..2668ea5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.10", + "version": "2.0.11", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ @@ -50,7 +50,7 @@ "lib": "lib/" }, "main": "lib/hprose.js", - "optionalDependencies": { "ws": "~1.0.1" }, + "optionalDependencies": { "ws": "~1.1.0" }, "devDependencies": { "promises-aplus-tests": "*" }, From 7caaae5050ac870062395a98d1bff0d05d962771 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 6 Jun 2016 20:06:22 +0800 Subject: [PATCH 029/131] Fixed Service --- lib/server/Service.js | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index b57d1ee..25330d6 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Jun 6, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -36,7 +36,10 @@ var Writer = global.hprose.Writer; function callService(args, context) { if (context.oneway) { setImmediate(function() { - context.method.apply(context.scope, args); + try { + context.method.apply(context.scope, args); + } + catch (e) {} }); if (context.async) { args[args.length - 1](null); @@ -855,9 +858,10 @@ function Service() { return _topics[topic]; } function delTimer(topics, id) { - if ('timer' in topics[id]) { - global.clearTimeout(topics[id].timer); - delete topics[id].timer; + var t = topics[id]; + if ('timer' in t) { + global.clearTimeout(t.timer); + delete t.timer; } } function offline(topics, topic, id) { @@ -875,10 +879,11 @@ function Service() { } } function setTimer(topics, topic, id) { - if (!('timer' in topics[id])) { - topics[id].timer = global.setTimeout(function() { + var t = topics[id]; + if (!('timer' in t)) { + t.timer = global.setTimeout(function() { offline(topics, topic, id); - }, topics[id].heartbeat); + }, t.heartbeat); } } function resetTimer(topics, topic, id) { @@ -889,23 +894,24 @@ function Service() { var topics = getTopics(topic); if (timeout > 0) { return request.timeout(timeout).catchError(function(e) { + var t = topics[id]; if (e instanceof TimeoutError) { var checkoffline = function() { - topics[id].timer = global.setTimeout( + t.timer = global.setTimeout( checkoffline, - topics[id].heartbeat + t.heartbeat ); - if (topics[id].count < 0) { + if (t.count < 0) { offline(topics, topic, id); } else { - topics[id].count--; + t.count--; } }; checkoffline(); } else { - topics[id].count--; + t.count--; } }); } @@ -914,7 +920,7 @@ function Service() { function publish(topic, options) { if (Array.isArray(topic)) { topic.forEach(function(t) { - publish(t, timeout); + publish(t, options); }); return; } From f03eb9c31319fd29d1f4dd55654de25336337a93 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 6 Jun 2016 21:12:50 +0800 Subject: [PATCH 030/131] Fixed lastIndexOf --- lib/common/Future.js | 1 + package.json | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 1a23d25..d9c3bf7 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -290,6 +290,7 @@ } function lastIndexOf(array, searchElement, fromIndex) { + if (fromIndex === undefined) fromIndex = array.length - 1; return all(array).then(function(array) { if (!isPromise(searchElement)) { searchElement = value(searchElement); diff --git a/package.json b/package.json index 2668ea5..d0f4b43 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.11", + "version": "2.0.12", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 8aec224fc2adb38f10e1cfb6e1f7c6a6b10c449d Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 6 Jun 2016 22:49:10 +0800 Subject: [PATCH 031/131] Fixed Future.prototype.lastIndexOf --- lib/common/Future.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index d9c3bf7..51910b8 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -290,12 +290,12 @@ } function lastIndexOf(array, searchElement, fromIndex) { - if (fromIndex === undefined) fromIndex = array.length - 1; return all(array).then(function(array) { if (!isPromise(searchElement)) { searchElement = value(searchElement); } return searchElement.then(function(searchElement) { + if (fromIndex === undefined) fromIndex = array.length - 1; return array.lastIndexOf(searchElement, fromIndex); }); }); From 6075e0f7d94975b95c5096a27a29c21ca3147505 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Tue, 7 Jun 2016 10:33:58 +0800 Subject: [PATCH 032/131] Fixed lastIndexOf --- lib/common/Future.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 51910b8..4c418fe 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -295,7 +295,9 @@ searchElement = value(searchElement); } return searchElement.then(function(searchElement) { - if (fromIndex === undefined) fromIndex = array.length - 1; + if (fromIndex === undefined) { + fromIndex = array.length - 1; + } return array.lastIndexOf(searchElement, fromIndex); }); }); From bbee7801a7a5ce7e2b59372af07d4fad8a760c9c Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 4 Jul 2016 01:49:14 +0800 Subject: [PATCH 033/131] Update to v2.0.13 --- .../middleware/batchlog/batchloghandler.js | 4 +- example/middleware/batchlog/loghandler.js | 4 +- example/middleware/cache/loghandler.js | 4 +- example/middleware/compressCache/server.js | 4 +- .../middleware/compressCache/sizehandler.js | 11 +-- .../middleware/compressCache/stathandler.js | 12 +-- example/middleware/log/loghandler.js | 4 +- example/middleware/log2/loghandler.js | 11 +-- lib/client/Client.js | 46 +++------- lib/server/Service.js | 83 ++++++++++--------- package.json | 4 +- 11 files changed, 83 insertions(+), 104 deletions(-) diff --git a/example/middleware/batchlog/batchloghandler.js b/example/middleware/batchlog/batchloghandler.js index d418f06..9218024 100644 --- a/example/middleware/batchlog/batchloghandler.js +++ b/example/middleware/batchlog/batchloghandler.js @@ -1,6 +1,8 @@ module.exports = function(batches, context, next) { console.log("before invoke:", batches); var result = next(batches, context); - console.log("after invoke:", batches, result); + result.then(function(result) { + console.log("after invoke:", batches, result); + }); return result; }; diff --git a/example/middleware/batchlog/loghandler.js b/example/middleware/batchlog/loghandler.js index 24b6cab..c77a599 100644 --- a/example/middleware/batchlog/loghandler.js +++ b/example/middleware/batchlog/loghandler.js @@ -1,6 +1,8 @@ module.exports = function(name, args, context, next) { console.log("before invoke:", name, args); var result = next(name, args, context); - console.log("after invoke:", name, args, result); + result.then(function(result) { + console.log("after invoke:", name, args, result); + }); return result; }; diff --git a/example/middleware/cache/loghandler.js b/example/middleware/cache/loghandler.js index 24b6cab..c77a599 100644 --- a/example/middleware/cache/loghandler.js +++ b/example/middleware/cache/loghandler.js @@ -1,6 +1,8 @@ module.exports = function(name, args, context, next) { console.log("before invoke:", name, args); var result = next(name, args, context); - console.log("after invoke:", name, args, result); + result.then(function(result) { + console.log("after invoke:", name, args, result); + }); return result; }; diff --git a/example/middleware/compressCache/server.js b/example/middleware/compressCache/server.js index 5ce4454..a58028e 100644 --- a/example/middleware/compressCache/server.js +++ b/example/middleware/compressCache/server.js @@ -7,9 +7,9 @@ function echo(value) { } var server = hprose.Server.create("http://0.0.0.0:8080/"); server.beforeFilter.use(stathandler('BeforeFilter')) - .use(sizehandler('Non compressed')); + .use(sizehandler('compressed')); server.addFilter(new CompressFilter('Lzp3')); server.afterFilter.use(stathandler('AfterFilter')) - .use(sizehandler('compressed')); + .use(sizehandler('Non compressed')); server.add(echo); server.start(); diff --git a/example/middleware/compressCache/sizehandler.js b/example/middleware/compressCache/sizehandler.js index d9e4da6..b1fe00c 100644 --- a/example/middleware/compressCache/sizehandler.js +++ b/example/middleware/compressCache/sizehandler.js @@ -3,14 +3,9 @@ module.exports = function(message) { return function(request, context, next) { console.log(message + ' request size: ' + request.length); var response = next(request, context); - if (hprose.Future.isPromise(response)) { - response.then(function(data) { - console.log(message + ' response size: ' + data.length); - }); - } - else { - console.log(message + ' response size: ' + response.length); - } + response.then(function(data) { + console.log(message + ' response size: ' + data.length); + }); return response; }; }; diff --git a/example/middleware/compressCache/stathandler.js b/example/middleware/compressCache/stathandler.js index d8c8d65..8b5e170 100644 --- a/example/middleware/compressCache/stathandler.js +++ b/example/middleware/compressCache/stathandler.js @@ -1,17 +1,11 @@ module.exports = function(message) { return function(request, context, next) { var start = Date.now(); - function showstat() { + var response = next(request, context); + response.then(function() { var end = Date.now(); console.log(message + ': It takes ' + (end - start) + ' ms.'); - } - var response = next(request, context); - if (hprose.Future.isPromise(response)) { - response.then(showstat); - } - else { - showstat(); - } + }); return response; }; }; diff --git a/example/middleware/log/loghandler.js b/example/middleware/log/loghandler.js index 24b6cab..c77a599 100644 --- a/example/middleware/log/loghandler.js +++ b/example/middleware/log/loghandler.js @@ -1,6 +1,8 @@ module.exports = function(name, args, context, next) { console.log("before invoke:", name, args); var result = next(name, args, context); - console.log("after invoke:", name, args, result); + result.then(function(result) { + console.log("after invoke:", name, args, result); + }); return result; }; diff --git a/example/middleware/log2/loghandler.js b/example/middleware/log2/loghandler.js index da05a2e..d26af91 100644 --- a/example/middleware/log2/loghandler.js +++ b/example/middleware/log2/loghandler.js @@ -2,13 +2,8 @@ var hprose = require('hprose'); module.exports = function(request, context, next) { console.log(hprose.BytesIO.toString(request)); var response = next(request, context); - if (hprose.Future.isPromise(response)) { - response.then(function(data) { - console.log(hprose.BytesIO.toString(data)); - }); - } - else { - console.log(hprose.BytesIO.toString(response)); - } + response.then(function(data) { + console.log(hprose.BytesIO.toString(data)); + }); return response; }; diff --git a/lib/client/Client.js b/lib/client/Client.js index 307555b..c610a1c 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Apr 1, 2016 * + * LastModified: Jul 4, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -1015,14 +1015,9 @@ function Client(uri, functions, settings) { _invokeHandler = _invokeHandlers.reduceRight( function(next, handler) { return function(name, args, context) { - try { - var result = handler(name, args, context, next); - if (Future.isFuture(result)) { return result; } - return Future.value(result); - } - catch (e) { - return Future.error(e); - } + return Future.sync(function() { + return handler(name, args, context, next); + }); }; }, invokeHandler); } @@ -1031,14 +1026,9 @@ function Client(uri, functions, settings) { _batchInvokeHandler = _batchInvokeHandlers.reduceRight( function(next, handler) { return function(batches, context) { - try { - var result = handler(batches, context, next); - if (Future.isFuture(result)) { return result; } - return Future.value(result); - } - catch (e) { - return Future.error(e); - } + return Future.sync(function() { + return handler(batches, context, next); + }); }; }, batchInvokeHandler); } @@ -1047,14 +1037,9 @@ function Client(uri, functions, settings) { _beforeFilterHandler = _beforeFilterHandlers.reduceRight( function(next, handler) { return function(request, context) { - try { - var response = handler(request, context, next); - if (Future.isFuture(response)) { return response; } - return Future.value(response); - } - catch (e) { - return Future.error(e); - } + return Future.sync(function() { + return handler(request, context, next); + }); }; }, beforeFilterHandler); } @@ -1063,14 +1048,9 @@ function Client(uri, functions, settings) { _afterFilterHandler = _afterFilterHandlers.reduceRight( function(next, handler) { return function(request, context) { - try { - var response = handler(request, context, next); - if (Future.isFuture(response)) { return response; } - return Future.value(response); - } - catch (e) { - return Future.error(e); - } + return Future.sync(function() { + return handler(request, context, next); + }); }; }, afterFilterHandler); } diff --git a/lib/server/Service.js b/lib/server/Service.js index 25330d6..d0c3861 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Jun 6, 2016 * + * LastModified: Jul 4, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -188,13 +188,9 @@ function Service() { }); } } - var result = invoke(name, args, context); - if (Future.isPromise(result)) { - return result.then(null, function(e) { - return sendError(e, context); - }); - } - return result; + return invoke(name, args, context).then(null, function(e) { + return sendError(e, context); + }); } catch (e) { return sendError(e, context); @@ -225,19 +221,15 @@ function Service() { } else { if (passContext) { args.push(context); } - return callService(args, context); + return Future.toPromise(callService(args, context)); } } function invoke(name, args, context) { - var result = _invokeHandler(name, args, context); - if (Future.isPromise(result)) { - return result.then(function(result) { - if (isError(result)) { throw result; } - return afterInvoke(name, args, context, result); - }); - } - return afterInvoke(name, args, context, result); + return _invokeHandler(name, args, context).then(function(result) { + if (isError(result)) { throw result; } + return afterInvoke(name, args, context, result); + }); } function afterInvoke(name, args, context, result) { @@ -347,34 +339,43 @@ function Service() { return stream.bytes; } + function delayError(e, context) { + var err = endError(e, context); + if (_errorDelay > 0) { + return Future.delayed(_errorDelay, err); + } + else { + return Promise.value(err); + } + } + function beforeFilterHandler(request, context) { var response; try { request = inputFilter(request, context); - response = _afterFilterHandler(request, context); - } - catch (e) { - response = endError(e, context); - if (_errorDelay > 0) { - response = Future.delayed(_errorDelay, response); - } - } - if (Future.isPromise(response)) { - return response.then(function(response) { - return outputFilter(response, context); + response = _afterFilterHandler(request, context).then(null, function(e) { + return delayError(e, context); }); } - else { - return outputFilter(response, context); + catch (e) { + response = delayError(e, context); } + return response.then(function(value) { + return outputFilter(value, context); + }); } function afterFilterHandler(request, context) { - var input = new BytesIO(request); - switch (input.readByte()) { - case Tags.TagCall: return doInvoke(input, context); - case Tags.TagEnd: return doFunctionList(context); - default: throw new Error('Wrong Request: \r\n' + BytesIO.toString(request)); + try { + var input = new BytesIO(request); + switch (input.readByte()) { + case Tags.TagCall: return doInvoke(input, context); + case Tags.TagEnd: return Future.value(doFunctionList(context)); + default: throw new Error('Wrong Request: \r\n' + BytesIO.toString(request)); + } + } + catch (e) { + return Future.error(e); } } @@ -1067,7 +1068,9 @@ function Service() { _beforeFilterHandler = _beforeFilterHandlers.reduceRight( function(next, handler) { return function(request, context) { - return handler(request, context, next); + return Future.sync(function() { + return handler(request, context, next); + }); }; }, beforeFilterHandler); } @@ -1076,7 +1079,9 @@ function Service() { _afterFilterHandler = _afterFilterHandlers.reduceRight( function(next, handler) { return function(request, context) { - return handler(request, context, next); + return Future.sync(function() { + return handler(request, context, next); + }); }; }, afterFilterHandler); } @@ -1085,7 +1090,9 @@ function Service() { _invokeHandler = _invokeHandlers.reduceRight( function(next, handler) { return function(name, args, context) { - return handler(name, args, context, next); + return Future.sync(function() { + return handler(name, args, context, next); + }); }; }, invokeHandler); } diff --git a/package.json b/package.json index d0f4b43..6858f6b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.12", + "version": "2.0.13", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ @@ -50,7 +50,7 @@ "lib": "lib/" }, "main": "lib/hprose.js", - "optionalDependencies": { "ws": "~1.1.0" }, + "optionalDependencies": { "ws": "~1.1.1" }, "devDependencies": { "promises-aplus-tests": "*" }, From 9d1baa08faf9dc720ff0b2d7f685461811b756c3 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 14 Jul 2016 01:02:46 +0800 Subject: [PATCH 034/131] Improved Socket & WebSocket Client --- example/tcpclient4.js | 41 +++++++++++++++++++++++++++++++++++ lib/client/SocketClient.js | 28 ++++++++++++++---------- lib/client/WebSocketClient.js | 4 ++-- 3 files changed, 59 insertions(+), 14 deletions(-) create mode 100644 example/tcpclient4.js diff --git a/example/tcpclient4.js b/example/tcpclient4.js new file mode 100644 index 0000000..fa61533 --- /dev/null +++ b/example/tcpclient4.js @@ -0,0 +1,41 @@ +/*jshint node:true, eqeqeq:true */ +'use strict'; + +var hprose = require('../lib/hprose.js'); +var client = hprose.Client.create('tcp://127.0.0.1:4321/', ['hello']); +client.fullDuplex = true; +client.maxPoolSize = 1; +var log = hprose.Future.wrap(console.log, console); +log(client.hello("async world1")); +log(client.hello("async world2")); +log(client.hello("async world3")); +log(client.hello("async world4")); +log(client.hello("async world5")); +log(client.hello("async world6")); + +// 串行异步 +client.hello("world1") +.then(function(result) { + console.log(result); + return client.hello("world2"); +}) +.then(function(result) { + console.log(result); + return client.hello("world3"); +}) +.then(function(result) { + console.log(result); + return client.hello("world4"); +}) +.then(function(result) { + console.log(result); + return client.hello("world5"); +}) +.then(function(result) { + console.log(result); + return client.hello("world6"); +}) +.then(function(result) { + console.log(result); + client.close(); +}); diff --git a/lib/client/SocketClient.js b/lib/client/SocketClient.js index 407a663..fbe312e 100644 --- a/lib/client/SocketClient.js +++ b/lib/client/SocketClient.js @@ -13,7 +13,7 @@ * * * Hprose Socket Client for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Jul 13, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -137,7 +137,7 @@ FullDuplexSocketTransporter.prototype = Object.create( fetch: { value: function() { var pool = this.pool; while (pool.length > 0) { - var conn = pool.shift(); + var conn = pool.pop(); if (conn.connected) { if (conn.count === 0) { conn.removeAllListeners('timeout'); @@ -192,12 +192,14 @@ FullDuplexSocketTransporter.prototype = Object.create( sendNext: { value: function(conn) { if (conn.count < 10) { if (this.requests.length > 0) { - var request = this.requests.shift(); + var request = this.requests.pop(); request.push(conn); this.send.apply(this, request); } else { - this.pool.push(conn); + if (this.pool.lastIndexOf(conn) < 0) { + this.pool.push(conn); + } } } } }, @@ -268,7 +270,7 @@ HalfDuplexSocketTransporter.prototype = Object.create( fetch: { value: function() { var pool = this.pool; while (pool.length > 0) { - var conn = pool.shift(); + var conn = pool.pop(); if (conn.connected) { conn.removeAllListeners('timeout'); conn.ref(); @@ -278,12 +280,14 @@ HalfDuplexSocketTransporter.prototype = Object.create( return null; } }, recycle: { value: function(conn) { - conn.unref(); - conn.setTimeout(this.client.poolTimeout, function() { - conn.connected = false; - conn.end(); - }); - this.pool.push(conn); + if (this.pool.lastIndexOf(conn) < 0) { + conn.unref(); + conn.setTimeout(this.client.poolTimeout, function() { + conn.connected = false; + conn.end(); + }); + this.pool.push(conn); + } } }, clean: { value: function(conn) { conn.removeAllListeners('receive'); @@ -295,7 +299,7 @@ HalfDuplexSocketTransporter.prototype = Object.create( } }, sendNext: { value: function(conn) { if (this.requests.length > 0) { - var request = this.requests.shift(); + var request = this.requests.pop(); request.push(conn); this.send.apply(this, request); } diff --git a/lib/client/WebSocketClient.js b/lib/client/WebSocketClient.js index b990366..22467cb 100644 --- a/lib/client/WebSocketClient.js +++ b/lib/client/WebSocketClient.js @@ -12,7 +12,7 @@ * * * Hprose WebSocket Client for HTML5. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Jul 14, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -80,7 +80,7 @@ function WebSocketClient(uri, functions, settings) { } if ((_count < 100) && (_requests.length > 0)) { ++_count; - var request = _requests.shift(); + var request = _requests.pop(); _ready.then(function() { send(request[0], request[1]); }); } if (_count === 0) { From ddd3d749a657238f00fe7ea16af43d8aa6c77937 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 14 Jul 2016 01:15:18 +0800 Subject: [PATCH 035/131] Update to v2.0.14 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 6858f6b..372996b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.13", + "version": "2.0.14", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From b2e09cf6ee81f9d2b6dc2e5a890d392540db4f3b Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 21 Jul 2016 00:03:48 +0800 Subject: [PATCH 036/131] Fixed push --- lib/server/Service.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index d0c3861..3f7d5e6 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Jul 4, 2016 * + * LastModified: Jul 21, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -1042,7 +1042,7 @@ function Service() { var args = arguments; var argc = args.length; var id, result; - if (argc < 2 && argc > 3) { + if (argc < 2 || argc > 3) { throw new Error('Wrong number of arguments'); } if (argc === 2) { From e31617020ad6aa5dfabdc021b6f11adf24fc9542 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Tue, 26 Jul 2016 11:37:58 +0800 Subject: [PATCH 037/131] Changed failswitch algorithm --- lib/client/Client.js | 19 ++++++++++++++----- package.json | 2 +- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index c610a1c..7bd71b7 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Jul 4, 2016 * + * LastModified: Jul 26, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -126,13 +126,22 @@ function Client(uri, functions, settings) { }); } - function retry(data, context, onsuccess, onerror) { - if (context.failswitch) { - if (++_index >= _uris.length) { - _index = 0; + function failswitch() { + var n = _uris.length; + if (n > 1) { + var i = _index + Math.floor(Math.random() * (n - 1)) + 1; + if (i >= n) { + i %= n; } + _index = i; _uri = _uris[_index]; } + } + + function retry(data, context, onsuccess, onerror) { + if (context.failswitch) { + failswitch(); + } if (context.idempotent) { if (--context.retry >= 0) { var interval = (context.retry >= 10) ? 500 : (10 - context.retry) * 500; diff --git a/package.json b/package.json index 372996b..5fd633d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.14", + "version": "2.0.15", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From b655233d8e9cfaac3a1e61b00bd8e4a09e225ee3 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Tue, 26 Jul 2016 11:38:07 +0800 Subject: [PATCH 038/131] Added ws_client.js --- example/ws_client.js | 49 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 example/ws_client.js diff --git a/example/ws_client.js b/example/ws_client.js new file mode 100644 index 0000000..d6950e0 --- /dev/null +++ b/example/ws_client.js @@ -0,0 +1,49 @@ +/*jshint node:true, eqeqeq:true */ +'use strict'; + +var hprose = require('../lib/hprose.js'); +var client = hprose.Client.create('ws://127.0.0.1:8080', []); +client.keepAlive = false; +client.simple = true; +var var_dump = hprose.Future.wrap(console.log, console); +var proxy = client.useService(['hello']); + +var_dump(proxy.hello('async world1')); +var_dump(proxy.hello('async world2')); +var_dump(proxy.hello('async world3')); +var_dump(proxy.hello('async world4')); +var_dump(proxy.hello('async world5')); +var_dump(proxy.hello('async world6')); + +proxy.hello("world1") +.then(function(result) { + console.log(result); + return proxy.hello("world2"); +}) +.then(function(result) { + console.log(result); + return proxy.hello("world3"); +}) +.then(function(result) { + console.log(result); + return proxy.hello("world4"); +}) +.then(function(result) { + console.log(result); + return proxy.hello("world5"); +}) +.then(function(result) { + console.log(result); + return proxy.hello("world6"); +}) +.then(function(result) { + console.log(result); +}); + +var_dump(proxy.hello('async world1')); +var_dump(proxy.hello('async world2')); +var_dump(proxy.hello('async world3')); +var_dump(proxy.hello('async world4')); +var_dump(proxy.hello('async world5')); +var_dump(proxy.hello('async world6')); + From d7475262f384d8371f35c783565cb708dc2535b4 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 28 Jul 2016 12:08:20 +0800 Subject: [PATCH 039/131] Fixed a bug of push service. --- lib/server/Service.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 3f7d5e6..ee7a841 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -33,6 +33,18 @@ var BytesIO = global.hprose.BytesIO; var Reader = global.hprose.Reader; var Writer = global.hprose.Writer; +function InvalidRequestError(message) { + Error.call(this); + this.message = message; + this.name = InvalidRequestError.name; + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(this, InvalidRequestError); + } +} + +InvalidRequestError.prototype = Object.create(Error.prototype); +InvalidRequestError.prototype.constructor = InvalidRequestError; + function callService(args, context) { if (context.oneway) { setImmediate(function() { @@ -912,6 +924,9 @@ function Service() { checkoffline(); } else { + if (e instanceof InvalidRequestError) { + return new Future(); + } t.count--; } }); @@ -962,7 +977,7 @@ function Service() { }); } if ('request' in topics[id]) { - topics[id].request.resolve(); + topics[id].request.reject(new InvalidRequestError()); } var request = new Future(); request.whenComplete(function() { topics[id].count--; }); From c9d9fad2355a9ceb1044c3aea58a8517763da42a Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 28 Jul 2016 13:52:02 +0800 Subject: [PATCH 040/131] Fixed a bug of push service. --- lib/server/Service.js | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/server/Service.js b/lib/server/Service.js index ee7a841..0a77303 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -993,6 +993,7 @@ function Service() { if ('request' in topics[id]) { topics[id].request.resolve(result); delete topics[id].request; + setTimer(topics, topic, id); return Future.value(true); } else { From 00a2fc58fa35d1e1587a30c0f07b717a6ec44217 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 28 Jul 2016 14:30:00 +0800 Subject: [PATCH 041/131] Update to 2.0.16 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 5fd633d..3db086f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.15", + "version": "2.0.16", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 075efd00d81a4464293acda63ff2729e52fcfecc Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 1 Aug 2016 12:18:00 +0800 Subject: [PATCH 042/131] Added multi parameters callback service support. --- lib/server/Service.js | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 0a77303..99185bb 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Jul 21, 2016 * + * LastModified: Aug 1, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -220,12 +220,34 @@ function Service() { if (context.async) { return Future.promise(function(resolve, reject) { if (passContext) { args.push(context); } - args.push(function(result) { - if (isError(result)) { - reject(result); - } - else { - resolve(result); + args.push(function() { + var args = arguments; + switch (args.length) { + case 0: resolve(undefined); break; + case 1: { + var result = args[0]; + if (isError(result)) { + reject(result); + } + else { + resolve(result); + } + } + default: { + var err = args[0]; + var result = args[1]; + if (err === undefined || err === null) { + resolve(result); + } + else { + if (isError(err)) { + reject(err); + } + else { + resolve(err); + } + } + } } }); callService(args, context); From 269c518a7b05caefc45b3274a323ad14e76ef365 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 1 Aug 2016 12:22:57 +0800 Subject: [PATCH 043/131] Update to v2.0.17 --- lib/server/Service.js | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 99185bb..28ea0c6 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -236,7 +236,7 @@ function Service() { default: { var err = args[0]; var result = args[1]; - if (err === undefined || err === null) { + if (err == null) { resolve(result); } else { diff --git a/package.json b/package.json index 3db086f..6686f7f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.16", + "version": "2.0.17", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 3f213ecf2d4512285a414e5d1d5bb9111675e5b4 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 1 Aug 2016 12:25:33 +0800 Subject: [PATCH 044/131] Update README --- README.md | 2 ++ README_zh_CN.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/README.md b/README.md index cd2e19a..714aaf1 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,8 @@ Through *Hprose*, You can conveniently and efficiently intercommunicate between This project is the implementation of Hprose for Node.js. +Hprose 2.0 for Node.js Documents(中文版): https://github.com/hprose/hprose-nodejs/wiki + ## Usage ### Http Server diff --git a/README_zh_CN.md b/README_zh_CN.md index 5ba9662..54c1510 100644 --- a/README_zh_CN.md +++ b/README_zh_CN.md @@ -57,6 +57,8 @@ 本项目是 Hprose 的 Node.js 语言版本实现。 +更多 Hprose 2.0 for Node.js 文档: https://github.com/hprose/hprose-nodejs/wiki + ## 使用 ### Http 服务器 From 96973cb19d0d7ae251fe58cb5a25f1ef44ed2a56 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 1 Aug 2016 12:31:46 +0800 Subject: [PATCH 045/131] Fixed missing break. --- lib/server/Service.js | 2 ++ package.json | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 28ea0c6..4a6deee 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -232,6 +232,7 @@ function Service() { else { resolve(result); } + break; } default: { var err = args[0]; @@ -247,6 +248,7 @@ function Service() { resolve(err); } } + break; } } }); diff --git a/package.json b/package.json index 6686f7f..3881ae7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.17", + "version": "2.0.18", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From e14c2a3f953fee99d677db960a38aa4a7b6b6caf Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 1 Aug 2016 12:33:29 +0800 Subject: [PATCH 046/131] Optimized callback --- lib/server/Service.js | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 4a6deee..340caab 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -240,13 +240,11 @@ function Service() { if (err == null) { resolve(result); } + else if (isError(err)) { + reject(err); + } else { - if (isError(err)) { - reject(err); - } - else { - resolve(err); - } + resolve(err); } break; } From 6cd83ca86be7b64ad6d900f64e32bdb4eb62fc66 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 11 Aug 2016 16:23:36 +0800 Subject: [PATCH 047/131] Update example --- example/timeclient.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/example/timeclient.js b/example/timeclient.js index ba193b3..75f98ef 100644 --- a/example/timeclient.js +++ b/example/timeclient.js @@ -1,7 +1,7 @@ /*jshint node:true, eqeqeq:true */ 'use strict'; -var hprose = require('hprose'); +var hprose = require('../lib/hprose'); var client = hprose.Client.create("http://127.0.0.1:8080/"); var count = 0; client.subscribe('time', function(date) { From 4fbc97cbfdb762a03d1e344f071cb5b10de19520 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 11 Aug 2016 16:23:55 +0800 Subject: [PATCH 048/131] Fixed Client in node.js 5.x --- lib/client/Client.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index 7bd71b7..e690e30 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Jul 26, 2016 * + * LastModified: Aug 11, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -824,7 +824,7 @@ function Client(uri, functions, settings) { setFunctions(stub, functions); } else { - if (typeof(Proxy) === 'undefined') { + if (typeof(Proxy) === 'undefined' || !('create' in Proxy)) { setImmediate(initService, stub); return _ready; } From 1f01eb54368c4c9d13eb2efd2edd847cc9645a3d Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 11 Aug 2016 16:24:12 +0800 Subject: [PATCH 049/131] Update getNextId --- lib/server/Service.js | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 340caab..b3554f7 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Aug 1, 2016 * + * LastModified: Aug 11, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -24,6 +24,7 @@ var util = require('util'); var EventEmitter = require('events').EventEmitter; var isError = require('../common/isError'); var TimeoutError = require('../common/TimeoutError'); +var crypto = require('crypto'); var setImmediate = global.setImmediate; var Future = global.hprose.Future; @@ -72,9 +73,17 @@ function getFuncName(func, obj) { return funcname; } -var nextid = 0; function getNextId() { - return (nextid < 0x7fffffff) ? ++nextid : nextid = 0; + var result = new Future(); + crypto.randomBytes(16, function(err, buf) { + if (err) { + result.reject(err); + } + else { + result.resolve(buf.toString('hex')); + } + }); + return result; } function Service() { From afef3c2869284402a636194fa76d629b20c2c614 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 11 Aug 2016 16:24:26 +0800 Subject: [PATCH 050/131] Update to v2.0.19 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 3881ae7..58562d1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.18", + "version": "2.0.19", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 5eafb1788b2e8abf5a9514d21865a408e487911d Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 12 Aug 2016 17:29:51 +0800 Subject: [PATCH 051/131] Improved Promises/A+ implementation --- lib/common/Future.js | 169 +++++++++++++++++-------------------------- package.json | 2 +- 2 files changed, 68 insertions(+), 103 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 4c418fe..22629fe 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Apr 11, 2016 * + * LastModified: Aug 12, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -375,6 +375,15 @@ }); } + function _resolve(onfulfill, next, x) { + if (onfulfill) { + _call(onfulfill, next, x); + } + else { + next.resolve(x); + } + } + function _reject(onreject, next, e) { if (onreject) { _call(onreject, next, e); @@ -384,82 +393,63 @@ } } - - function _resolve(onfulfill, onreject, self, next, x) { - function resolvePromise(y) { - _resolve(onfulfill, onreject, self, next, y); - } - function rejectPromise(r) { - _reject(onreject, next, r); - } - if (isPromise(x)) { - if (x === self) { - rejectPromise(new TypeError('Self resolution')); + Object.defineProperties(Future.prototype, { + _value: { writable: true }, + _reason: { writable: true }, + _state: { value: PENDING, writable: true }, + resolve: { value: function(value) { + if (value === this) { + this.reject(new TypeError('Self resolution')); return; } - x.then(resolvePromise, rejectPromise); - return; - } - if ((x !== null) && - (typeof x === 'object') || - (typeof x === 'function')) { - var then; - try { - then = x.then; - } - catch (e) { - rejectPromise(e); + if (isPromise(value)) { + value.fill(this); return; } - if (typeof then === 'function') { - var notrun = true; + if ((value !== null) && + (typeof value === 'object') || + (typeof value === 'function')) { + var then; try { - then.call(x, function(y) { - if (notrun) { - notrun = false; - resolvePromise(y); - } - }, function(r) { + then = value.then; + } + catch (e) { + this.reject(e); + return; + } + if (typeof then === 'function') { + var notrun = true; + try { + var self = this; + then.call(value, function(y) { + if (notrun) { + notrun = false; + self.resolve(y); + } + }, function(r) { + if (notrun) { + notrun = false; + self.reject(r); + } + }); + return; + } + catch (e) { if (notrun) { notrun = false; - rejectPromise(r); + this.reject(e); } - }); - return; - } - catch (e) { - if (notrun) { - notrun = false; - rejectPromise(e); } + return; } - return; } - } - if (onfulfill) { - _call(onfulfill, next, x); - } - else { - next.resolve(x); - } - } - - Object.defineProperties(Future.prototype, { - _value: { writable: true }, - _reason: { writable: true }, - _state: { value: PENDING, writable: true }, - resolve: { value: function(value) { if (this._state === PENDING) { this._state = FULFILLED; this._value = value; var subscribers = this._subscribers; while (subscribers.length > 0) { var subscriber = subscribers.shift(); - _resolve(subscriber.onfulfill, - subscriber.onreject, - this, - subscriber.next, - value); + _resolve(subscriber.onfulfill, subscriber.next, value); } } } }, @@ -470,43 +460,28 @@ var subscribers = this._subscribers; while (subscribers.length > 0) { var subscriber = subscribers.shift(); - if (subscriber.onreject) { - _call(subscriber.onreject, - subscriber.next, - reason); - } - else { - subscriber.next.reject(reason); - } + _reject(subscriber.onreject, subscriber.next, reason); } } } }, then: { value: function(onfulfill, onreject) { if (typeof onfulfill !== 'function') { onfulfill = null; } if (typeof onreject !== 'function') { onreject = null; } - if (onfulfill || onreject) { - var next = new Future(); - if (this._state === FULFILLED) { - _resolve(onfulfill, onreject, this, next, this._value); - } - else if (this._state === REJECTED) { - if (onreject) { - _call(onreject, next, this._reason); - } - else { - next.reject(this._reason); - } - } - else { - this._subscribers.push({ - onfulfill: onfulfill, - onreject: onreject, - next: next - }); - } - return next; + var next = new Future(); + if (this._state === FULFILLED) { + _resolve(onfulfill, next, this._value); } - return this; + else if (this._state === REJECTED) { + _reject(onreject, next, this._reason); + } + else { + this._subscribers.push({ + onfulfill: onfulfill, + onreject: onreject, + next: next + }); + } + return next; } }, done: { value: function(onfulfill, onreject) { this.then(onfulfill, onreject).then(null, function(error) { @@ -542,18 +517,8 @@ } }, whenComplete: { value: function(action) { return this.then( - function(v) { - var f = action(); - if (f === undefined) { return v; } - f = isPromise(f) ? f : value(f); - return f.then(function() { return v; }); - }, - function(e) { - var f = action(); - if (f === undefined) { throw e; } - f = isPromise(f) ? f : value(f); - return f.then(function() { throw e; }); - } + function(v) { action(); return v; }, + function(e) { action(); throw e; } ); } }, complete: { value: function(oncomplete) { diff --git a/package.json b/package.json index 58562d1..09ce3cc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.19", + "version": "2.0.20", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 115b855ca2e5434827de9be263bf1fe49f8a6a6e Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 20 Aug 2016 13:03:45 +0800 Subject: [PATCH 052/131] Added express support for WebSocketServer. --- lib/server/WebSocketServer.js | 11 ++++++----- package.json | 2 +- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/lib/server/WebSocketServer.js b/lib/server/WebSocketServer.js index 8d071da..4513e32 100644 --- a/lib/server/WebSocketServer.js +++ b/lib/server/WebSocketServer.js @@ -13,7 +13,7 @@ * * * Hprose WebSocket Server for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Aug 20, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -26,12 +26,13 @@ var http = require('http'); var https = require('https'); var WebSocketService = global.hprose.WebSocketService; -function WebSocketServer(options, tlsOptions) { +function WebSocketServer(options, tlsOptions, handler) { WebSocketService.call(this); var self = this; - var httpserver = (tlsOptions ? - https.createServer(tlsOptions, self.handle) : - http.createServer(self.handle)); + if (!handler) handler = this.handle; + var httpserver = tlsOptions ? + https.createServer(tlsOptions, handler) : + http.createServer(handler); var host = options.host; var port = options.port; delete options.host; diff --git a/package.json b/package.json index 09ce3cc..c33e7d1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.20", + "version": "2.0.21", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 9136f8cae437f4e40e22ac1cfe369b7e4ec3030d Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 20 Aug 2016 13:09:07 +0800 Subject: [PATCH 053/131] Added express support for WebSocketServer. --- lib/server/Server.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/server/Server.js b/lib/server/Server.js index 9657554..6b65c42 100644 --- a/lib/server/Server.js +++ b/lib/server/Server.js @@ -13,7 +13,7 @@ * * * Hprose Server for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Aug 20, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -25,7 +25,7 @@ var HttpServer = global.hprose.HttpServer; var SocketServer = global.hprose.SocketServer; var WebSocketServer = global.hprose.WebSocketServer; -function create(uri, tlsOptions) { +function create(uri, tlsOptions, handler) { var parser = parse(uri); var protocol = parser.protocol; var options = {}; @@ -68,13 +68,13 @@ function create(uri, tlsOptions) { if (parser.path) { options.path = parser.path; } - return new WebSocketServer(options, tlsOptions); + return new WebSocketServer(options, tlsOptions, handler); } throw new Error('The ' + protocol + ' server isn\'t implemented.'); } -function Server(uri, tlsOptions) { - return create(uri, tlsOptions); +function Server(uri, tlsOptions, handler) { + return create(uri, tlsOptions, handler); } Object.defineProperty(Server, 'create', { value: create }); From 5a7a262da9177a2f3552a4f422de10fea5958626 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 24 Aug 2016 18:08:48 +0800 Subject: [PATCH 054/131] Added failswitch parameter for subscribe --- lib/client/Client.js | 14 +++++++------- package.json | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index e690e30..b544666 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Aug 11, 2016 * + * LastModified: Aug 24, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -875,9 +875,9 @@ function Client(uri, functions, settings) { } return null; } - // subscribe(name, callback, timeout) - // subscribe(name, id, callback, timeout) - function subscribe(name, id, callback, timeout) { + // subscribe(name, callback, timeout, failswitch) + // subscribe(name, id, callback, timeout, failswitch) + function subscribe(name, id, callback, timeout, failswitch) { if (typeof name !== s_string) { throw new TypeError('topic name must be a string.'); } @@ -896,7 +896,7 @@ function Client(uri, functions, settings) { _id = autoId(); } _id.then(function(id) { - subscribe(name, id, callback, timeout); + subscribe(name, id, callback, timeout, failswitch); }); return; } @@ -905,7 +905,7 @@ function Client(uri, functions, settings) { } if (Future.isPromise(id)) { id.then(function(id) { - subscribe(name, id, callback, timeout); + subscribe(name, id, callback, timeout, failswitch); }); return; } @@ -915,7 +915,7 @@ function Client(uri, functions, settings) { var cb = function() { _invoke(self, name, [id, topic.handler, cb, { idempotent: true, - failswitch: false, + failswitch: failswitch, timeout: timeout }], false); }; diff --git a/package.json b/package.json index c33e7d1..66b5691 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.21", + "version": "2.0.22", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From ed1fcba236816abd33c8133274a4db801720ec39 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 4 Sep 2016 14:06:42 +0800 Subject: [PATCH 055/131] Update to 2.0.23 --- lib/client/Client.js | 83 +++++++++++++++++++++++++++++++++---------- lib/server/Service.js | 13 ++++++- package.json | 2 +- 3 files changed, 77 insertions(+), 21 deletions(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index b544666..9e9d51f 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Aug 24, 2016 * + * LastModified: Sep 4, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -60,7 +60,7 @@ function Client(uri, functions, settings) { // private members var _uri, - _uris = [], + _uriList = [], _index = -1, _byref = false, _simple = false, @@ -68,10 +68,12 @@ function Client(uri, functions, settings) { _retry = 10, _idempotent = false, _failswitch = false, + _failround = 0, _lock = false, _tasks = [], _useHarmonyMap = false, _onerror = noop, + _onfailswitch = noop, _filters = [], _batch = false, _batches = [], @@ -127,29 +129,44 @@ function Client(uri, functions, settings) { } function failswitch() { - var n = _uris.length; + var n = _uriList.length; if (n > 1) { - var i = _index + Math.floor(Math.random() * (n - 1)) + 1; + var i = _index + 1; if (i >= n) { - i %= n; + i = 0; + _failround++; } _index = i; - _uri = _uris[_index]; + _uri = _uriList[_index]; } + else { + _failround++; + } + _onfailswitch(self); + self.emit('failswitch', self); } function retry(data, context, onsuccess, onerror) { if (context.failswitch) { failswitch(); } - if (context.idempotent) { - if (--context.retry >= 0) { - var interval = (context.retry >= 10) ? 500 : (10 - context.retry) * 500; + if (context.idempotent && (context.retried < context.retry)) { + var interval = ++context.retried * 500; + if (context.failswitch) { + interval -= (_uriList.length - 1) * 500; + } + if (interval > 5000) { + interval = 5000; + } + if (interval > 0) { global.setTimeout(function() { sendAndReceive(data, context, onsuccess, onerror); }, interval); - return true; } + else { + sendAndReceive(data, context, onsuccess, onerror); + } + return true; } return false; } @@ -157,6 +174,7 @@ function Client(uri, functions, settings) { function initService(stub) { var context = { retry: _retry, + retried: 0, idempotent: true, failswitch: true, timeout: _timeout, @@ -270,6 +288,7 @@ function Client(uri, functions, settings) { simple: _simple, timeout: _timeout, retry: _retry, + retried: 0, idempotent: _idempotent, failswitch: _failswitch, oneway: false, @@ -499,6 +518,7 @@ function Client(uri, functions, settings) { var context = { timeout: _timeout, retry: _retry, + retried: 0, idempotent: _idempotent, failswitch: _failswitch, oneway: false, @@ -678,15 +698,43 @@ function Client(uri, functions, settings) { _onerror = value; } } + function getOnFailswitch() { + return _onfailswitch; + } + function setOnFailswitch(value) { + if (typeof(value) === s_function) { + _onfailswitch = value; + } + } function getUri() { return _uri; } + function getUriList() { + return _uriList; + } + function setUriList(uriList) { + if (typeof(uriList) === s_string) { + _uriList = [uriList]; + } + else if (Array.isArray(uriList)) { + _uriList = uriList.slice(0); + _uriList.sort(function() { return Math.random() - 0.5; }); + } + else { + return; + } + _index = 0; + _uri = _uriList[_index]; + } function getFailswitch() { return _failswitch; } function setFailswitch(value) { _failswitch = !!value; } + function getFailround() { + return _failround; + } function getTimeout() { return _timeout; } @@ -1090,9 +1138,12 @@ function Client(uri, functions, settings) { Object.defineProperties(this, { '#': { value: autoId }, onerror: { get: getOnError, set: setOnError }, + onfailswitch: { get: getOnFailswitch, set: setOnFailswitch }, uri: { get: getUri }, + uriList: { get: getUriList, set: setUriList }, id: { get: getId }, failswitch: { get: getFailswitch, set: setFailswitch }, + failround: { get: getFailround }, timeout: { get: getTimeout, set: setTimeout }, retry: { get: getRetry, set: setRetry }, idempotent: { get: getIdempotent, set: setIdempotent }, @@ -1126,15 +1177,9 @@ function Client(uri, functions, settings) { } }); } - if (typeof(uri) === s_string) { - _uris = [uri]; - _index = 0; - useService(uri, functions); - } - else if (Array.isArray(uri)) { - _uris = uri; - _index = Math.floor(Math.random() * _uris.length); - useService(_uris[_index], functions); + if (uri) { + setUriList(uri); + useService(functions); } } } diff --git a/lib/server/Service.js b/lib/server/Service.js index b3554f7..3d59603 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Aug 11, 2016 * + * LastModified: Sep 3, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -529,6 +529,17 @@ function Service() { return true; } + function remove(alias) { + var name = alias.toLowerCase(); + if (_calls[name]) { + var index = _name.indexOf(alias); + if (index >= 0) { + _name.splice(index, 1); + } + delete _calls[name]; + } + } + function addFunction(func, alias, options) { if (typeof(func) !== 'function') { throw new Error('Argument func must be a function'); diff --git a/package.json b/package.json index 66b5691..9915176 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.22", + "version": "2.0.23", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From d75176d82c9284ccb2144e50aaa2b59e9e440632 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 17 Sep 2016 17:03:12 +0800 Subject: [PATCH 056/131] Fixed timeout bug of HalfDuplex socket client. --- example/timeoutclient.js | 17 +++++++++++++++++ example/timeoutserver.js | 19 +++++++++++++++++++ lib/client/SocketClient.js | 5 +++-- 3 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 example/timeoutclient.js create mode 100644 example/timeoutserver.js diff --git a/example/timeoutclient.js b/example/timeoutclient.js new file mode 100644 index 0000000..c698bc3 --- /dev/null +++ b/example/timeoutclient.js @@ -0,0 +1,17 @@ +/*jshint node:true, eqeqeq:true */ +'use strict'; + +var hprose = require('../lib/hprose.js'); +var client = hprose.Client.create('ws://127.0.0.1:4321/', ['sum']); +// client.fullDuplex = false; +client.keepAlive = false; +client.timeout = 600; + +client.sum(1, 2); +client.sum(1, 2).then(function(result) { + console.log("1 + 2 = " + result); +}).catch(function() { + client.sum(2, 3, function(result) { + console.log("2 + 3 = " + result); + }, { timeout: 20000 }); +}) \ No newline at end of file diff --git a/example/timeoutserver.js b/example/timeoutserver.js new file mode 100644 index 0000000..9c48237 --- /dev/null +++ b/example/timeoutserver.js @@ -0,0 +1,19 @@ +/*jshint node:true, eqeqeq:true */ +'use strict'; + +var hprose = require('../lib/hprose.js'); + +function sum(a, b) { + var promise = new hprose.Future(); + setTimeout(function() { + promise.resolve(a + b); + }, 1000); + return promise; +} + +var server = hprose.Server.create("ws://0.0.0.0:4321"); +server.addFunction(sum); +process.on('SIGINT', function() { + server.stop(); +}); +server.start(); diff --git a/lib/client/SocketClient.js b/lib/client/SocketClient.js index fbe312e..0b79037 100644 --- a/lib/client/SocketClient.js +++ b/lib/client/SocketClient.js @@ -13,7 +13,7 @@ * * * Hprose Socket Client for Node.js. * * * - * LastModified: Jul 13, 2016 * + * LastModified: Sep 17, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -313,7 +313,8 @@ HalfDuplexSocketTransporter.prototype = Object.create( if (timeout > 0) { conn.timeoutId = global.setTimeout(function() { self.clean(conn); - self.recycle(conn); + conn.connected = false; + conn.end(); future.reject(new TimeoutError('timeout')); }, timeout); } From 07a54bd3a3d648377beeb2a4ada6ed5140f376c4 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 17 Sep 2016 17:03:37 +0800 Subject: [PATCH 057/131] Fixed memory leak when client timeout shorter than push server. --- lib/server/Service.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 3d59603..5002195 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Sep 3, 2016 * + * LastModified: Sep 17, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -966,9 +966,6 @@ function Service() { checkoffline(); } else { - if (e instanceof InvalidRequestError) { - return new Future(); - } t.count--; } }); From 8ef6479eee60b12103887754487c0c3ba14852e7 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 17 Sep 2016 17:04:06 +0800 Subject: [PATCH 058/131] Fixed error report when client timeout shorter than push server. --- lib/server/SocketService.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/server/SocketService.js b/lib/server/SocketService.js index 38d375a..6859e6a 100644 --- a/lib/server/SocketService.js +++ b/lib/server/SocketService.js @@ -13,7 +13,7 @@ * * * Hprose Socket Service for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Sep 17, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -155,9 +155,11 @@ function SocketService() { socket.on('end', noop); socket.on('error', function(e) { try { - self.emit('sendError', e, context); - if (self.onSendError) { - self.onSendError(e, context); + if (e.code != "EPIPE") { + self.emit('sendError', e, context); + if (self.onSendError) { + self.onSendError(e, context); + } } } catch(e) {} From b29003dd462be3a5ed8f97fbe2df3f2eceff11f4 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 22 Sep 2016 10:03:08 +0800 Subject: [PATCH 059/131] Improved push service --- example/timeoutclient.js | 2 +- example/timeoutserver.js | 2 +- lib/server/Service.js | 21 +++------------------ 3 files changed, 5 insertions(+), 20 deletions(-) diff --git a/example/timeoutclient.js b/example/timeoutclient.js index c698bc3..4e905da 100644 --- a/example/timeoutclient.js +++ b/example/timeoutclient.js @@ -2,7 +2,7 @@ 'use strict'; var hprose = require('../lib/hprose.js'); -var client = hprose.Client.create('ws://127.0.0.1:4321/', ['sum']); +var client = hprose.Client.create('tcp://127.0.0.1:4321/', ['sum']); // client.fullDuplex = false; client.keepAlive = false; client.timeout = 600; diff --git a/example/timeoutserver.js b/example/timeoutserver.js index 9c48237..a32ba96 100644 --- a/example/timeoutserver.js +++ b/example/timeoutserver.js @@ -11,7 +11,7 @@ function sum(a, b) { return promise; } -var server = hprose.Server.create("ws://0.0.0.0:4321"); +var server = hprose.Server.create("tcp://0.0.0.0:4321"); server.addFunction(sum); process.on('SIGINT', function() { server.stop(); diff --git a/lib/server/Service.js b/lib/server/Service.js index 5002195..2199868 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Sep 17, 2016 * + * LastModified: Sep 22, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -34,18 +34,6 @@ var BytesIO = global.hprose.BytesIO; var Reader = global.hprose.Reader; var Writer = global.hprose.Writer; -function InvalidRequestError(message) { - Error.call(this); - this.message = message; - this.name = InvalidRequestError.name; - if (typeof Error.captureStackTrace === 'function') { - Error.captureStackTrace(this, InvalidRequestError); - } -} - -InvalidRequestError.prototype = Object.create(Error.prototype); -InvalidRequestError.prototype.constructor = InvalidRequestError; - function callService(args, context) { if (context.oneway) { setImmediate(function() { @@ -949,8 +937,8 @@ function Service() { var topics = getTopics(topic); if (timeout > 0) { return request.timeout(timeout).catchError(function(e) { - var t = topics[id]; if (e instanceof TimeoutError) { + var t = topics[id]; var checkoffline = function() { t.timer = global.setTimeout( checkoffline, @@ -965,9 +953,6 @@ function Service() { }; checkoffline(); } - else { - t.count--; - } }); } return request; @@ -1016,7 +1001,7 @@ function Service() { }); } if ('request' in topics[id]) { - topics[id].request.reject(new InvalidRequestError()); + topics[id].request.resolve(null); } var request = new Future(); request.whenComplete(function() { topics[id].count--; }); From 220ba2506c9095b5119c6f137b0d2bfd62b55e02 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 22 Sep 2016 13:26:48 +0800 Subject: [PATCH 060/131] Improved push service --- lib/server/Service.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 2199868..9da3430 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -938,8 +938,8 @@ function Service() { if (timeout > 0) { return request.timeout(timeout).catchError(function(e) { if (e instanceof TimeoutError) { - var t = topics[id]; var checkoffline = function() { + var t = topics[id]; t.timer = global.setTimeout( checkoffline, t.heartbeat From 5ed98eecbef3bc1e4a4ba96f3922dca0002096c7 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 28 Sep 2016 14:16:34 +0800 Subject: [PATCH 061/131] Fixed an error caused by https://bugs.webkit.org/show_bug.cgi?id=80797 --- lib/common/Helper.js | 12 ++++++------ lib/io/BytesIO.js | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/common/Helper.js b/lib/common/Helper.js index 2126608..b212142 100644 --- a/lib/common/Helper.js +++ b/lib/common/Helper.js @@ -13,7 +13,7 @@ * * * Hprose Helper for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Sep 28, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -55,17 +55,17 @@ bytes = new Uint8Array(bytes); } var n = bytes.length; - if (n < 100000) { + if (n < 0xFFFF) { return String.fromCharCode.apply(String, getCharCodes(bytes)); } - var remain = n & 0xFFFF; - var count = n >> 16; + var remain = n & 0x7FFF; + var count = n >> 15; var a = new Array(remain ? count + 1 : count); for (var i = 0; i < count; ++i) { - a[i] = String.fromCharCode.apply(String, getCharCodes(bytes.subarray(i << 16, (i + 1) << 16))); + a[i] = String.fromCharCode.apply(String, getCharCodes(bytes.subarray(i << 15, (i + 1) << 15))); } if (remain) { - a[count] = String.fromCharCode.apply(String, getCharCodes(bytes.subarray(count << 16, n))); + a[count] = String.fromCharCode.apply(String, getCharCodes(bytes.subarray(count << 15, n))); } return a.join(''); } diff --git a/lib/io/BytesIO.js b/lib/io/BytesIO.js index 80ead95..32b6bfa 100644 --- a/lib/io/BytesIO.js +++ b/lib/io/BytesIO.js @@ -13,7 +13,7 @@ * * * Hprose BytesIO for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Sep 28, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -142,7 +142,7 @@ function readShortString(bytes, n) { function readLongString(bytes, n) { var buf = []; - var charCodes = new Uint16Array(0xFFFF); + var charCodes = new Uint16Array(0x8000); var i = 0, off = 0; for (var len = bytes.length; i < n && off < len; i++) { var unit = bytes[off++]; @@ -198,7 +198,7 @@ function readLongString(bytes, n) { default: throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16)); } - if (i >= 65534) { + if (i >= 0x7FFF - 1) { var size = i + 1; buf.push(String.fromCharCode.apply(String, charCodes.subarray(0, size))); n -= size; @@ -214,7 +214,7 @@ function readLongString(bytes, n) { function readString(bytes, n) { if (n === undefined || n === null || (n < 0)) { n = bytes.length; } if (n === 0) { return ['', 0]; } - return ((n < 100000) ? + return ((n < 0xFFFF) ? readShortString(bytes, n) : readLongString(bytes, n)); } From e7f1361e6ad54ca930776f59f9b2fcd3b3f52758 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 30 Sep 2016 15:29:46 +0800 Subject: [PATCH 062/131] Changed setImmediate to process.nextTick --- lib/client/Client.js | 7 ++-- lib/common/Future.js | 9 +++-- lib/common/setImmediate.js | 65 ---------------------------------- lib/hprose.js | 3 +- lib/server/Service.js | 7 ++-- lib/server/WebSocketService.js | 5 ++- package.json | 2 +- 7 files changed, 14 insertions(+), 84 deletions(-) delete mode 100644 lib/common/setImmediate.js diff --git a/lib/client/Client.js b/lib/client/Client.js index 9e9d51f..1535cc0 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Sep 4, 2016 * + * LastModified: Sep 30, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -25,7 +25,6 @@ var util = require('util'); var parse = require('url').parse; var EventEmitter = require('events').EventEmitter; -var setImmediate = global.setImmediate; var Tags = global.hprose.Tags; var ResultMode = global.hprose.ResultMode; var BytesIO = global.hprose.BytesIO; @@ -457,7 +456,7 @@ function Client(uri, functions, settings) { return function() { if (sync) { _lock = false; - setImmediate(function(tasks) { + process.nextTick(function(tasks) { tasks.forEach(function(task) { if ('settings' in task) { endBatch(task.settings) @@ -873,7 +872,7 @@ function Client(uri, functions, settings) { } else { if (typeof(Proxy) === 'undefined' || !('create' in Proxy)) { - setImmediate(initService, stub); + process.nextTick(initService, stub); return _ready; } stub = Proxy.create(new HproseProxy(setFunction)); diff --git a/lib/common/Future.js b/lib/common/Future.js index 22629fe..9667f1f 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Aug 12, 2016 * + * LastModified: Sep 30, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -28,7 +28,6 @@ var REJECTED = 2; var hasPromise = 'Promise' in global; - var setImmediate = global.setImmediate; var setTimeout = global.setTimeout; var clearTimeout = global.clearTimeout; var foreach = Function.prototype.call.bind(Array.prototype.forEach); @@ -42,7 +41,7 @@ }); var self = this; if (typeof computation === 'function') { - setImmediate(function() { + process.nextTick(function() { try { self.resolve(computation()); } @@ -364,7 +363,7 @@ }); function _call(callback, next, x) { - setImmediate(function() { + process.nextTick(function() { try { var r = callback(x); next.resolve(r); @@ -485,7 +484,7 @@ } }, done: { value: function(onfulfill, onreject) { this.then(onfulfill, onreject).then(null, function(error) { - setImmediate(function() { throw error; }); + process.nextTick(function() { throw error; }); }); } }, inspect: { value: function() { diff --git a/lib/common/setImmediate.js b/lib/common/setImmediate.js deleted file mode 100644 index 9a2d668..0000000 --- a/lib/common/setImmediate.js +++ /dev/null @@ -1,65 +0,0 @@ -/**********************************************************\ -| | -| hprose | -| | -| Official WebSite: http://www.hprose.com/ | -| http://www.hprose.org/ | -| | -\**********************************************************/ - -/**********************************************************\ - * * - * hprose/common/setImmediate.js * - * * - * setImmediate for Node.js. * - * * - * LastModified: Mar 3, 2016 * - * Author: Ma Bingyao * - * * -\**********************************************************/ - -(function() { - 'use strict'; - - if (global.setImmediate) { return; } - - var slice = Function.prototype.call.bind(Array.prototype.slice); - var nextId = 1; - var tasks = {}; - - function wrap(handler) { - var args = slice(arguments, 1); - return function() { - handler.apply(undefined, args); - }; - } - - function run(handleId) { - var task = tasks[handleId]; - if (task) { - try { - task(); - } - finally { - clear(handleId); - } - } - } - - function create(args) { - tasks[nextId] = wrap.apply(undefined, args); - return nextId++; - } - - function clear(handleId) { - delete tasks[handleId]; - } - - global.setImmediate = function() { - var handleId = create(arguments); - global.process.nextTick( wrap( run, handleId ) ); - return handleId; - }; - - global.clearImmediate = clear; -})(); diff --git a/lib/hprose.js b/lib/hprose.js index 24adf9c..cb7fa57 100644 --- a/lib/hprose.js +++ b/lib/hprose.js @@ -13,7 +13,7 @@ * * * hprose for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Sep 30, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -25,7 +25,6 @@ global.hprose = global.hprose || Object.create(null); require('./common/Helper.js'); require('./common/Polyfill.js'); require('./common/HarmonyMaps.js'); -require('./common/setImmediate.js'); require('./common/Future.js'); require('./common/ResultMode.js'); diff --git a/lib/server/Service.js b/lib/server/Service.js index 9da3430..71f31af 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Sep 22, 2016 * + * LastModified: Sep 30, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -26,7 +26,6 @@ var isError = require('../common/isError'); var TimeoutError = require('../common/TimeoutError'); var crypto = require('crypto'); -var setImmediate = global.setImmediate; var Future = global.hprose.Future; var ResultMode = global.hprose.ResultMode; var Tags = global.hprose.Tags; @@ -36,7 +35,7 @@ var Writer = global.hprose.Writer; function callService(args, context) { if (context.oneway) { - setImmediate(function() { + process.nextTick(function() { try { context.method.apply(context.scope, args); } @@ -991,7 +990,7 @@ function Service() { } else { topics[id] = { messages: [], count: 1, heartbeat: heartbeat }; - setImmediate(function() { + process.nextTick(function() { if (_events[topic] instanceof EventEmitter) { _events[topic].emit('subscribe', id, self); } diff --git a/lib/server/WebSocketService.js b/lib/server/WebSocketService.js index 8f5db49..0779cee 100644 --- a/lib/server/WebSocketService.js +++ b/lib/server/WebSocketService.js @@ -13,7 +13,7 @@ * * * Hprose WebSocket Service for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Sep 30, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -22,7 +22,6 @@ var util = require('util'); -var setImmediate = global.setImmediate; var HttpService = global.hprose.HttpService; var BytesIO = global.hprose.BytesIO; var Future = global.hprose.Future; @@ -126,7 +125,7 @@ function WebSocketService() { var bytes = new BytesIO(data); var id = bytes.readInt32BE(); var request = bytes.read(bytes.length - 4); - setImmediate(function() { + process.nextTick(function() { var context = { httpserver: self.httpserver, server: self.server, diff --git a/package.json b/package.json index 9915176..25796d2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.23", + "version": "2.0.24", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 1ce5be251fb4ab8cddcd337053bbc568ad8c1058 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 12 Oct 2016 19:34:07 +0800 Subject: [PATCH 063/131] Added isSubscribed and subscribedList --- lib/client/Client.js | 43 +++++++++++++++++++++++++++++-------------- lib/common/Helper.js | 13 ++++++++++++- 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index 1535cc0..616121c 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Sep 30, 2016 * + * LastModified: Oct 12, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -32,6 +32,7 @@ var Writer = global.hprose.Writer; var Reader = global.hprose.Reader; var Future = global.hprose.Future; var slice = Function.prototype.call.bind(Array.prototype.slice); +var isObjectEmpty = global.hprose.isObjectEmpty; var GETFUNCTIONS = new Uint8Array(1); GETFUNCTIONS[0] = Tags.TagEnd; @@ -909,16 +910,12 @@ function Client(uri, functions, settings) { function ready(onComplete, onError) { return _ready.then(onComplete, onError); } - function getTopic(name, id, create) { + function getTopic(name, id) { if (_topics[name]) { var topics = _topics[name]; if (topics[id]) { return topics[id]; } - return null; - } - if (create) { - _topics[name] = Object.create(null); } return null; } @@ -936,13 +933,13 @@ function Client(uri, functions, settings) { throw new TypeError('callback must be a function.'); } } + if (!_topics[name]) { + _topics[name] = Object.create(null); + } if (typeof id === s_function) { timeout = callback; callback = id; - if (_id === null) { - _id = autoId(); - } - _id.then(function(id) { + autoId().then(function(id) { subscribe(name, id, callback, timeout, failswitch); }); return; @@ -957,7 +954,7 @@ function Client(uri, functions, settings) { return; } if (timeout === undefined) { timeout = _timeout; } - var topic = getTopic(name, id, true); + var topic = getTopic(name, id); if (topic === null) { var cb = function() { _invoke(self, name, [id, topic.handler, cb, { @@ -968,7 +965,7 @@ function Client(uri, functions, settings) { }; topic = { handler: function(result) { - var topic = getTopic(name, id, false); + var topic = getTopic(name, id); if (topic) { if (result !== null) { var callbacks = topic.callbacks; @@ -979,7 +976,7 @@ function Client(uri, functions, settings) { catch (e) {} } } - if (getTopic(name, id, false) !== null) { cb(); } + if (getTopic(name, id) !== null) { cb(); } } }, callbacks: [callback] @@ -1056,12 +1053,28 @@ function Client(uri, functions, settings) { else { delTopic(_topics[name], id, callback); } + if (isObjectEmpty(_topics[name])) { + delete _topics[name]; + } + } + function isSubscribed(name) { + return !!_topics[name]; + } + function subscribedList() { + var list = []; + for (var name in _topics) { + list.push(name); + } + return list; } function getId() { return _id; } function autoId() { - return _invoke(self, '#', [], false); + if (_id === null) { + _id = _invoke(self, '#', [], false); + } + return _id; } autoId.sync = true; autoId.idempotent = true; @@ -1161,6 +1174,8 @@ function Client(uri, functions, settings) { ready: { value: ready }, subscribe: {value: subscribe }, unsubscribe: {value: unsubscribe }, + isSubscribed: { value : isSubscribed }, + subscribedList: { value : subscribedList }, use: { value: use }, batch: { value: batch }, beforeFilter: { value: beforeFilter }, diff --git a/lib/common/Helper.js b/lib/common/Helper.js index b212142..6a6802d 100644 --- a/lib/common/Helper.js +++ b/lib/common/Helper.js @@ -13,7 +13,7 @@ * * * Hprose Helper for Node.js. * * * - * LastModified: Sep 28, 2016 * + * LastModified: Oct 12, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -79,9 +79,20 @@ return data; } + var isObjectEmpty = function (obj) { + if (obj) { + var prop; + for (prop in obj) { + return false; + } + } + return true; + } + global.hprose.generic = generic; global.hprose.toBinaryString = toBinaryString; global.hprose.toUint8Array = toUint8Array; global.hprose.toArray = toArray; + global.hprose.isObjectEmpty = isObjectEmpty; })(); From 2237248b21f04e319364c904311f65ca9b28be8d Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 12 Oct 2016 19:50:24 +0800 Subject: [PATCH 064/131] Update to 2.0.25 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 25796d2..b5b4605 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.24", + "version": "2.0.25", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From e636567c38c7f88e6d17ab804d5b98db5b5bee56 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 13 Oct 2016 00:02:55 +0800 Subject: [PATCH 065/131] Added push promise data support. --- lib/server/Service.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 71f31af..0315098 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Sep 30, 2016 * + * LastModified: Oct 13, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -1009,6 +1009,11 @@ function Service() { }, topic); } function _push(topic, id, result) { + if (Future.isPromise(result)) { + return result.then(function(result) { + return _push(topic, id, result); + }); + } var topics = getTopics(topic); if (!(id in topics)) { return Future.value(false); From ebf07ba313d434b279ea1cd9d2947b1c81187207 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 13 Oct 2016 00:04:50 +0800 Subject: [PATCH 066/131] Update to 2.0.26 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index b5b4605..56877a6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.25", + "version": "2.0.26", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From d62c234a0f8720512831de37edcd18c0125ab822 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 16 Oct 2016 10:19:22 +0800 Subject: [PATCH 067/131] Revert "Added push promise data support." This reverts commit e636567c38c7f88e6d17ab804d5b98db5b5bee56. --- lib/server/Service.js | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 0315098..71f31af 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Oct 13, 2016 * + * LastModified: Sep 30, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -1009,11 +1009,6 @@ function Service() { }, topic); } function _push(topic, id, result) { - if (Future.isPromise(result)) { - return result.then(function(result) { - return _push(topic, id, result); - }); - } var topics = getTopics(topic); if (!(id in topics)) { return Future.value(false); From 80ae313715f70fe45552ee8c0381b435b739c6cc Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 16 Oct 2016 10:40:36 +0800 Subject: [PATCH 068/131] Improved push promise data. --- lib/server/Service.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 71f31af..74795fd 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Sep 30, 2016 * + * LastModified: Oct 16, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -1009,6 +1009,12 @@ function Service() { }, topic); } function _push(topic, id, result) { + if (Future.isPromise(result)) { + var __push = function(result) { + return _push(topic, id, result); + } + return result.then(__push, __push); + } var topics = getTopics(topic); if (!(id in topics)) { return Future.value(false); From 6c29bd996f480dd72ec0a5a2a20f492af6b0fff8 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 16 Oct 2016 11:51:43 +0800 Subject: [PATCH 069/131] Update to v2.0.27 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 56877a6..21f6f00 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.26", + "version": "2.0.27", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 0e13748734c0a4e7107d21bc936b33bd4905ab1b Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 21 Oct 2016 13:57:55 +0800 Subject: [PATCH 070/131] Fixed a bug of Future. --- lib/common/Future.js | 6 +++--- package.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 9667f1f..2c10953 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Sep 30, 2016 * + * LastModified: Oct 21, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -61,7 +61,7 @@ } function toPromise(obj) { - return (isPromise(obj) ? obj : value(obj)); + return (isFuture(obj) ? obj : value(obj)); } function delayed(duration, value) { @@ -401,7 +401,7 @@ this.reject(new TypeError('Self resolution')); return; } - if (isPromise(value)) { + if (isFuture(value)) { value.fill(this); return; } diff --git a/package.json b/package.json index 21f6f00..974b691 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.27", + "version": "2.0.28", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 8145ed713265b2fc787b2c555228a79b17993c5a Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 23 Oct 2016 13:16:29 +0800 Subject: [PATCH 071/131] Improved BytesIO.js --- lib/io/BytesIO.js | 68 +++++++++++++++-------------------------------- 1 file changed, 22 insertions(+), 46 deletions(-) diff --git a/lib/io/BytesIO.js b/lib/io/BytesIO.js index 32b6bfa..381ff99 100644 --- a/lib/io/BytesIO.js +++ b/lib/io/BytesIO.js @@ -13,7 +13,7 @@ * * * Hprose BytesIO for Node.js. * * * - * LastModified: Sep 28, 2016 * + * LastModified: Oct 23, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -97,21 +97,17 @@ function readShortString(bytes, n) { if (off < len) { charCodes[i] = ((unit & 0x1F) << 6) | (bytes[off++] & 0x3F); + break; } - else { - throw new Error('Unfinished UTF-8 octet sequence'); - } - break; + throw new Error('Unfinished UTF-8 octet sequence'); case 14: if (off + 1 < len) { charCodes[i] = ((unit & 0x0F) << 12) | ((bytes[off++] & 0x3F) << 6) | (bytes[off++] & 0x3F); + break; } - else { - throw new Error('Unfinished UTF-8 octet sequence'); - } - break; + throw new Error('Unfinished UTF-8 octet sequence'); case 15: if (off + 2 < len) { var rune = (((unit & 0x07) << 18) | @@ -121,15 +117,11 @@ function readShortString(bytes, n) { if (0 <= rune && rune <= 0xFFFFF) { charCodes[i++] = (((rune >> 10) & 0x03FF) | 0xD800); charCodes[i] = ((rune & 0x03FF) | 0xDC00); + break; } - else { - throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); - } - } - else { - throw new Error('Unfinished UTF-8 octet sequence'); + throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); } - break; + throw new Error('Unfinished UTF-8 octet sequence'); default: throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16)); } @@ -162,21 +154,17 @@ function readLongString(bytes, n) { if (off < len) { charCodes[i] = ((unit & 0x1F) << 6) | (bytes[off++] & 0x3F); + break; } - else { - throw new Error('Unfinished UTF-8 octet sequence'); - } - break; + throw new Error('Unfinished UTF-8 octet sequence'); case 14: if (off + 1 < len) { charCodes[i] = ((unit & 0x0F) << 12) | ((bytes[off++] & 0x3F) << 6) | (bytes[off++] & 0x3F); + break; } - else { - throw new Error('Unfinished UTF-8 octet sequence'); - } - break; + throw new Error('Unfinished UTF-8 octet sequence'); case 15: if (off + 2 < len) { var rune = (((unit & 0x07) << 18) | @@ -186,15 +174,11 @@ function readLongString(bytes, n) { if (0 <= rune && rune <= 0xFFFFF) { charCodes[i++] = (((rune >> 10) & 0x03FF) | 0xD800); charCodes[i] = ((rune & 0x03FF) | 0xDC00); + break; } - else { - throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); - } - } - else { - throw new Error('Unfinished UTF-8 octet sequence'); + throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); } - break; + throw new Error('Unfinished UTF-8 octet sequence'); default: throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16)); } @@ -239,19 +223,15 @@ function readStringAsBytes(bytes, n) { case 13: if (off < len) { off++; + break; } - else { - throw new Error('Unfinished UTF-8 octet sequence'); - } - break; + throw new Error('Unfinished UTF-8 octet sequence'); case 14: if (off + 1 < len) { off += 2; + break; } - else { - throw new Error('Unfinished UTF-8 octet sequence'); - } - break; + throw new Error('Unfinished UTF-8 octet sequence'); case 15: if (off + 2 < len) { var rune = (((unit & 0x07) << 18) | @@ -260,15 +240,11 @@ function readStringAsBytes(bytes, n) { (bytes[off++] & 0x3F)) - 0x10000; if (0 <= rune && rune <= 0xFFFFF) { i++; + break; } - else { - throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); - } + throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); } - else { - throw new Error('Unfinished UTF-8 octet sequence'); - } - break; + throw new Error('Unfinished UTF-8 octet sequence'); default: throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16)); } From a170377de596f55f7478765441d6988649c1ea0c Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 14 Nov 2016 10:49:55 +0800 Subject: [PATCH 072/131] Improved retry. --- lib/client/Client.js | 29 +++++++++++++++-------------- package.json | 2 +- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index 616121c..652ff93 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Oct 12, 2016 * + * LastModified: Nov 14, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -117,15 +117,17 @@ function Client(uri, functions, settings) { } function afterFilterHandler(request, context) { - return self.sendAndReceive(request, context); + return self.sendAndReceive(request, context).catchError(function(e) { + var response = retry(request, context); + if (response !== null) { + return response; + } + throw e; + }); } function sendAndReceive(request, context, onsuccess, onerror) { - _beforeFilterHandler(request, context) - .then(onsuccess, function(e) { - if (retry(request, context, onsuccess, onerror)) { return; } - onerror(e); - }); + _beforeFilterHandler(request, context).then(onsuccess, onerror); } function failswitch() { @@ -146,7 +148,7 @@ function Client(uri, functions, settings) { self.emit('failswitch', self); } - function retry(data, context, onsuccess, onerror) { + function retry(data, context) { if (context.failswitch) { failswitch(); } @@ -159,16 +161,15 @@ function Client(uri, functions, settings) { interval = 5000; } if (interval > 0) { - global.setTimeout(function() { - sendAndReceive(data, context, onsuccess, onerror); - }, interval); + return Future.delayed(interval, function() { + return afterFilterHandler(data, context); + }); } else { - sendAndReceive(data, context, onsuccess, onerror); + return afterFilterHandler(data, context); } - return true; } - return false; + return null; } function initService(stub) { diff --git a/package.json b/package.json index 974b691..eda571c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.28", + "version": "2.0.29", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From f33ce808883858dcb8023efe109e72a7ce531847 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Tue, 15 Nov 2016 13:21:40 +0800 Subject: [PATCH 073/131] Fixed isPromise --- lib/common/Future.js | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 2c10953..47e0dd9 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -57,7 +57,7 @@ } function isPromise(obj) { - return isFuture(obj) || (hasPromise && (obj instanceof global.Promise) && (typeof (obj.then === 'function'))); + return 'function' === typeof obj.then; } function toPromise(obj) { diff --git a/package.json b/package.json index eda571c..d6d7389 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.29", + "version": "2.0.30", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 273455234cfb3570c69f12a424ce4fe62c598557 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 17 Nov 2016 10:48:36 +0800 Subject: [PATCH 074/131] Added hprose.promisify Added hprose.thunkify Added hprose.co Added hprose.co.wrap & hprose.wrap Improved attempt, toPromise, wrap, forEach, every, some, filter, map, find, findIndex --- lib/common/Future.js | 170 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 163 insertions(+), 7 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 47e0dd9..7e550cd 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Oct 21, 2016 * + * LastModified: Nov 17, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -60,10 +60,6 @@ return 'function' === typeof obj.then; } - function toPromise(obj) { - return (isFuture(obj) ? obj : value(obj)); - } - function delayed(duration, value) { var computation = (typeof value === 'function') ? value : @@ -194,9 +190,10 @@ } function attempt(handler/*, arg1, arg2, ... */) { + var thisArg = (function() { return this; })(); var args = slice(arguments, 1); return all(args).then(function(args) { - return handler.apply(undefined, args); + return handler.apply(thisArg, args); }); } @@ -207,39 +204,188 @@ }); } + function isGenerator(obj) { + return 'function' == typeof obj.next && 'function' == typeof obj.throw; + } + + function isGeneratorFunction(obj) { + if (!obj) { + return false; + } + var constructor = obj.constructor; + if (!constructor) { + return false; + } + if ('GeneratorFunction' === constructor.name || + 'GeneratorFunction' === constructor.displayName) { + return true; + } + return isGenerator(constructor.prototype); + } + + function thunkToPromise(fn) { + var thisArg = (function() { return this; })(); + var future = new Future(); + fn.call(thisArg, function(err, res) { + if (arguments.length < 2) { + if (err instanceof Error) { + return future.reject(err); + } + return future.resolve(err); + } + if (err) return future.reject(err); + if (arguments.length > 2) { + res = slice(arguments, 1); + } + future.resolve(res); + }); + return future; + } + + function thunkify(fn) { + return function() { + var args = slice(arguments, 0); + var thisArg = this; + var results = new Future(); + args.push(function() { + thisArg = this; + results.resolve(arguments); + }); + try { + fn.apply(this, args); + } + catch (err) { + results.resolve([err]); + } + return function(done) { + results.then(function(results) { + done.apply(thisArg, results); + }); + }; + }; + } + + function promisify(fn) { + return function() { + var args = slice(arguments, 0); + var results = new Future(); + args.push(function(err, res) { + if (arguments.length < 2) { + if (err instanceof Error) { + return results.reject(err); + } + return results.resolve(err); + } + if (err) return results.reject(err); + if (arguments.length > 2) { + res = slice(arguments, 1); + } + results.resolve(res); + }); + try { + fn.apply(this, args); + } + catch (err) { + results.reject(err); + } + return results; + }; + } + + function toPromise(obj) { + if (!obj) return value(obj); + if (isPromise(obj)) return obj; + if (isGeneratorFunction(obj) || isGenerator(obj)) return co(obj); + if ('function' == typeof obj) return thunkToPromise(obj); + return value(obj); + } + + function co(gen) { + var thisArg = (function() { return this; })(); + if (typeof gen === 'function') { + var args = slice(arguments, 1); + gen = gen.apply(thisArg, args); + } + var future = new Future(); + + function onFulfilled(res) { + try { + next(gen.next(res)); + } + catch (e) { + future.reject(e); + } + } + + function onRejected(err) { + try { + next(gen.throw(err)); + } + catch (e) { + return future.reject(e); + } + } + + function next(ret) { + if (ret.done) { + future.resolve(ret.value); + } + else { + toPromise(ret.value).then(onFulfilled, onRejected); + } + } + + if (!gen || typeof gen.next !== 'function') { + return future.resolve(gen); + } + onFulfilled(); + + return future; + } + function wrap(handler, thisArg) { return function() { + thisArg = thisArg || this; return all(arguments).then(function(args) { - return handler.apply(thisArg, args); + var result = handler.apply(thisArg, args); + if (isGeneratorFunction(result)) { + return co.call(thisArg, result); + } + return result; }); }; } function forEach(array, callback, thisArg) { + thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.forEach(callback, thisArg); }); } function every(array, callback, thisArg) { + thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.every(callback, thisArg); }); } function some(array, callback, thisArg) { + thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.some(callback, thisArg); }); } function filter(array, callback, thisArg) { + thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.filter(callback, thisArg); }); } function map(array, callback, thisArg) { + thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.map(callback, thisArg); }); @@ -314,12 +460,14 @@ } function find(array, predicate, thisArg) { + thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.find(predicate, thisArg); }); } function findIndex(array, predicate, thisArg) { + thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { return array.findIndex(predicate, thisArg); }); @@ -346,6 +494,9 @@ settle: { value: settle }, attempt: { value: attempt }, run: { value: run }, + thunkify: { value: thunkify }, + promisify: { value: promisify }, + co: { value: co }, wrap: { value: wrap }, // for array forEach: { value: forEach }, @@ -653,6 +804,11 @@ global.hprose.Future = Future; + global.hprose.thunkify = thunkify; + global.hprose.promisify = promisify; + global.hprose.co = co; + global.hprose.co.wrap = global.hprose.wrap = wrap; + function Completer() { var future = new Future(); Object.defineProperties(this, { From 8c4e95aabcd9901303d2772215eb70dd1dc28e00 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 17 Nov 2016 20:22:12 +0800 Subject: [PATCH 075/131] Improved code --- lib/common/Future.js | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 7e550cd..6da26fc 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -205,7 +205,7 @@ } function isGenerator(obj) { - return 'function' == typeof obj.next && 'function' == typeof obj.throw; + return 'function' == typeof obj.next && 'function' == typeof obj['throw']; } function isGeneratorFunction(obj) { @@ -233,7 +233,9 @@ } return future.resolve(err); } - if (err) return future.reject(err); + if (err) { + return future.reject(err); + } if (arguments.length > 2) { res = slice(arguments, 1); } @@ -276,7 +278,9 @@ } return results.resolve(err); } - if (err) return results.reject(err); + if (err) { + return results.reject(err); + } if (arguments.length > 2) { res = slice(arguments, 1); } @@ -293,10 +297,18 @@ } function toPromise(obj) { - if (!obj) return value(obj); - if (isPromise(obj)) return obj; - if (isGeneratorFunction(obj) || isGenerator(obj)) return co(obj); - if ('function' == typeof obj) return thunkToPromise(obj); + if (!obj) { + return value(obj); + } + if (isPromise(obj)) { + return obj; + } + if (isGeneratorFunction(obj) || isGenerator(obj)) { + return co(obj); + } + if ('function' == typeof obj) { + return thunkToPromise(obj); + } return value(obj); } @@ -319,7 +331,7 @@ function onRejected(err) { try { - next(gen.throw(err)); + next(gen['throw'](err)); } catch (e) { return future.reject(e); From 13c7d20986c653501c268337ae346e12d5a56ef0 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 17 Nov 2016 20:36:00 +0800 Subject: [PATCH 076/131] Added regenerator-runtime.js --- lib/hprose.js | 2 + lib/utils/regenerator-runtime.js | 669 +++++++++++++++++++++++++++++++ 2 files changed, 671 insertions(+) create mode 100644 lib/utils/regenerator-runtime.js diff --git a/lib/hprose.js b/lib/hprose.js index cb7fa57..d7bdfb7 100644 --- a/lib/hprose.js +++ b/lib/hprose.js @@ -52,6 +52,8 @@ require('./server/Server.js'); require('./filter/JSONRPCClientFilter.js'); require('./filter/JSONRPCServiceFilter.js'); +require('./utils/regenerator-runtime.js'); + global.HproseCompleter = global.hprose.Completer; global.HproseFuture = global.hprose.Future; global.HproseResultMode = global.hprose.ResultMode; diff --git a/lib/utils/regenerator-runtime.js b/lib/utils/regenerator-runtime.js new file mode 100644 index 0000000..4ec72f1 --- /dev/null +++ b/lib/utils/regenerator-runtime.js @@ -0,0 +1,669 @@ +/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * https://raw.github.com/facebook/regenerator/master/LICENSE file. An + * additional grant of patent rights can be found in the PATENTS file in + * the same directory. + */ + +!(function(global) { + "use strict"; + + var hasOwn = Object.prototype.hasOwnProperty; + var undefined; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + var inModule = typeof module === "object"; + var runtime = global.regeneratorRuntime; + if (runtime) { + if (inModule) { + // If regeneratorRuntime is defined globally and we're in a module, + // make the exports object identical to regeneratorRuntime. + module.exports = runtime; + } + // Don't bother evaluating the rest of this file if the runtime was + // already defined globally. + return; + } + + // Define the runtime globally (as expected by generated code) as either + // module.exports (if we're in a module) or a new, empty object. + runtime = global.regeneratorRuntime = inModule ? module.exports : {}; + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + runtime.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype; + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction"; + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + prototype[method] = function(arg) { + return this._invoke(method, arg); + }; + }); + } + + runtime.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + runtime.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + if (!(toStringTagSymbol in genFun)) { + genFun[toStringTagSymbol] = "GeneratorFunction"; + } + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `value instanceof AwaitArgument` to determine if the yielded value is + // meant to be awaited. Some may consider the name of this method too + // cutesy, but they are curmudgeons. + runtime.awrap = function(arg) { + return new AwaitArgument(arg); + }; + + function AwaitArgument(arg) { + this.arg = arg; + } + + function AsyncIterator(generator) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value instanceof AwaitArgument) { + return Promise.resolve(value.arg).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return Promise.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. If the Promise is rejected, however, the + // result for this iteration will be rejected with the same + // reason. Note that rejections of yielded Promises are not + // thrown back into the generator function, as is the case + // when an awaited Promise is rejected. This difference in + // behavior between yield and await is important, because it + // allows the consumer to decide what to do with the yielded + // rejection (swallow it and continue, manually .throw it back + // into the generator, abandon iteration, whatever). With + // await, by contrast, there is no opportunity to examine the + // rejection reason outside the generator function, so the + // only option is to throw it from the await expression, and + // let the generator function handle the exception. + result.value = unwrapped; + resolve(result); + }, reject); + } + } + + if (typeof process === "object" && process.domain) { + invoke = process.domain.bind(invoke); + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new Promise(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + runtime.async = function(innerFn, outerFn, self, tryLocsList) { + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList) + ); + + return runtime.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + while (true) { + var delegate = context.delegate; + if (delegate) { + if (method === "return" || + (method === "throw" && delegate.iterator[method] === undefined)) { + // A return or throw (when the delegate iterator has no throw + // method) always terminates the yield* loop. + context.delegate = null; + + // If the delegate iterator has a return method, give it a + // chance to clean up. + var returnMethod = delegate.iterator["return"]; + if (returnMethod) { + var record = tryCatch(returnMethod, delegate.iterator, arg); + if (record.type === "throw") { + // If the return method threw an exception, let that + // exception prevail over the original return or throw. + method = "throw"; + arg = record.arg; + continue; + } + } + + if (method === "return") { + // Continue with the outer return, now that the delegate + // iterator has been terminated. + continue; + } + } + + var record = tryCatch( + delegate.iterator[method], + delegate.iterator, + arg + ); + + if (record.type === "throw") { + context.delegate = null; + + // Like returning generator.throw(uncaught), but without the + // overhead of an extra function call. + method = "throw"; + arg = record.arg; + continue; + } + + // Delegate generator ran and handled its own exceptions so + // regardless of what the method was, we continue as if it is + // "next" with an undefined arg. + method = "next"; + arg = undefined; + + var info = record.arg; + if (info.done) { + context[delegate.resultName] = info.value; + context.next = delegate.nextLoc; + } else { + state = GenStateSuspendedYield; + return info; + } + + context.delegate = null; + } + + if (method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = arg; + + } else if (method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw arg; + } + + if (context.dispatchException(arg)) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + method = "next"; + arg = undefined; + } + + } else if (method === "return") { + context.abrupt("return", arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + var info = { + value: record.arg, + done: context.done + }; + + if (record.arg === ContinueSentinel) { + if (context.delegate && method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + arg = undefined; + } + } else { + return info; + } + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(arg) call above. + method = "throw"; + arg = record.arg; + } + } + }; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + Gp[iteratorSymbol] = function() { + return this; + }; + + Gp[toStringTagSymbol] = "Generator"; + + Gp.toString = function() { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + runtime.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + runtime.values = values; + + function doneResult() { + return { value: undefined, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined; + this.done = false; + this.delegate = null; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + return !!caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.next = finallyEntry.finallyLoc; + } else { + this.complete(record); + } + + return ContinueSentinel; + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = record.arg; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + return ContinueSentinel; + } + }; +})( + // Among the various tricks for obtaining a reference to the global + // object, this seems to be the most reliable technique that does not + // use indirect eval (which violates Content Security Policy). + typeof global === "object" ? global : + typeof window === "object" ? window : + typeof self === "object" ? self : this +); From 3865d54cd6bb3a11e9bd85f61a0a5050b04519aa Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 17 Nov 2016 20:48:50 +0800 Subject: [PATCH 077/131] Added testco and testthunkify --- example/testco.js | 24 ++++++++++++++++++++++++ example/testthunkify.js | 14 ++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 example/testco.js create mode 100644 example/testthunkify.js diff --git a/example/testco.js b/example/testco.js new file mode 100644 index 0000000..e0623cb --- /dev/null +++ b/example/testco.js @@ -0,0 +1,24 @@ +var co = require('../lib/hprose.js').co; + +function* sleep() { + return new Promise(function(resolve) { + setTimeout(resolve, 1); + }); +}; + +co(function*() { + + for(var i = 0; true; ++i) { + yield sleep(); + + if (i % 10000 === 0) { + console.log(process.memoryUsage()); + } + + } + +}).then(function() { + console.log('finished') +}, function(err) { + console.log('caught error: ', err.stack); +}); \ No newline at end of file diff --git a/example/testthunkify.js b/example/testthunkify.js new file mode 100644 index 0000000..43d63ee --- /dev/null +++ b/example/testthunkify.js @@ -0,0 +1,14 @@ +var thunkify = require('../lib/hprose.js').thunkify; + +var delay = thunkify(function (time, callback) { + setTimeout(callback, time); +}); + +var result = delay(100); +setTimeout(function () { + console.log('a'); + result(function () { + console.log('c'); + }); + console.log('b'); +}, 500); \ No newline at end of file From dc92ea18b7112ac66e1e407b6b89c3a7e5ebe277 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 17 Nov 2016 20:48:58 +0800 Subject: [PATCH 078/131] Update to 2.0.31 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index d6d7389..f8f6aa1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.30", + "version": "2.0.31", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From e462cb013cf34026986301e0eb45f78f620bf40c Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 18 Nov 2016 01:19:50 +0800 Subject: [PATCH 079/131] Improved WebSocketClient --- lib/client/WebSocketClient.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/client/WebSocketClient.js b/lib/client/WebSocketClient.js index 22467cb..0515b90 100644 --- a/lib/client/WebSocketClient.js +++ b/lib/client/WebSocketClient.js @@ -12,7 +12,7 @@ * * * Hprose WebSocket Client for HTML5. * * * - * LastModified: Jul 14, 2016 * + * LastModified: Nov 16, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -99,7 +99,6 @@ function WebSocketClient(uri, functions, settings) { _count = 0; } function connect() { - _ready = new Future(); self.setOption('perMessageDeflate', false); ws = new WebSocket(self.uri, self.options); ws.on('open', onopen); @@ -111,7 +110,7 @@ function WebSocketClient(uri, functions, settings) { if (ws === null || ws.readyState === WebSocket.CLOSING || ws.readyState === WebSocket.CLOSED) { - connect(); + _ready = new Future(); } var id = getNextId(); var future = new Future(); @@ -133,6 +132,11 @@ function WebSocketClient(uri, functions, settings) { else { _requests.push([id, request]); } + if (ws === null || + ws.readyState === WebSocket.CLOSING || + ws.readyState === WebSocket.CLOSED) { + connect(); + } if (env.oneway) { future.resolve(); } return future; } From c7a233459bb5b6f1259c60485a89056345a94280 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 18 Nov 2016 01:31:50 +0800 Subject: [PATCH 080/131] Improved WebSocketClient --- lib/client/WebSocketClient.js | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/lib/client/WebSocketClient.js b/lib/client/WebSocketClient.js index 0515b90..6218789 100644 --- a/lib/client/WebSocketClient.js +++ b/lib/client/WebSocketClient.js @@ -12,7 +12,7 @@ * * * Hprose WebSocket Client for HTML5. * * * - * LastModified: Nov 16, 2016 * + * LastModified: Nov 18, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -99,6 +99,7 @@ function WebSocketClient(uri, functions, settings) { _count = 0; } function connect() { + _ready = new Future(); self.setOption('perMessageDeflate', false); ws = new WebSocket(self.uri, self.options); ws.on('open', onopen); @@ -107,11 +108,6 @@ function WebSocketClient(uri, functions, settings) { ws.on('close', onclose); } function sendAndReceive(request, env) { - if (ws === null || - ws.readyState === WebSocket.CLOSING || - ws.readyState === WebSocket.CLOSED) { - _ready = new Future(); - } var id = getNextId(); var future = new Future(); _futures[id] = future; @@ -125,6 +121,11 @@ function WebSocketClient(uri, functions, settings) { return e instanceof TimeoutError; }); } + if (ws === null || + ws.readyState === WebSocket.CLOSING || + ws.readyState === WebSocket.CLOSED) { + connect(); + } if (_count < 100) { ++_count; _ready.then(function() { send(id, request); }); @@ -132,11 +133,6 @@ function WebSocketClient(uri, functions, settings) { else { _requests.push([id, request]); } - if (ws === null || - ws.readyState === WebSocket.CLOSING || - ws.readyState === WebSocket.CLOSED) { - connect(); - } if (env.oneway) { future.resolve(); } return future; } From f8917a39436c363564a4e45ae3a440bda861c8f2 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 18 Nov 2016 01:36:56 +0800 Subject: [PATCH 081/131] Improved WebSocketClient --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index f8f6aa1..cb6dbf9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.31", + "version": "2.0.32", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From f8f962dab4a6a5b6250cddf17908079787366bef Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 18 Nov 2016 16:28:46 +0800 Subject: [PATCH 082/131] Fixed toPromise and wrap --- lib/common/Future.js | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 6da26fc..17ee148 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Nov 17, 2016 * + * LastModified: Nov 18, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -205,6 +205,9 @@ } function isGenerator(obj) { + if (!obj) { + return false; + } return 'function' == typeof obj.next && 'function' == typeof obj['throw']; } @@ -224,6 +227,9 @@ } function thunkToPromise(fn) { + if (isGeneratorFunction(fn) || isGenerator(fn)) { + return co(fn); + } var thisArg = (function() { return this; })(); var future = new Future(); fn.call(thisArg, function(err, res) { @@ -306,9 +312,6 @@ if (isGeneratorFunction(obj) || isGenerator(obj)) { return co(obj); } - if ('function' == typeof obj) { - return thunkToPromise(obj); - } return value(obj); } @@ -343,7 +346,9 @@ future.resolve(ret.value); } else { - toPromise(ret.value).then(onFulfilled, onRejected); + (('function' == typeof ret.value) ? + thunkToPromise(ret.value) : + toPromise(ret.value)).then(onFulfilled, onRejected); } } @@ -360,7 +365,7 @@ thisArg = thisArg || this; return all(arguments).then(function(args) { var result = handler.apply(thisArg, args); - if (isGeneratorFunction(result)) { + if (isGeneratorFunction(result) || isGenerator(result)) { return co.call(thisArg, result); } return result; From 04bd0788b8bb6a4f3f4ae6f38b08a7dbfde8188d Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 18 Nov 2016 17:06:00 +0800 Subject: [PATCH 083/131] Update to v2.0.33 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index cb6dbf9..e4682df 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.32", + "version": "2.0.33", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From c45fc1c6d729d2fb6968063a7983b60d7f982bf4 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 19 Nov 2016 00:04:12 +0800 Subject: [PATCH 084/131] Improved Future.complete --- lib/common/Future.js | 3 ++- package.json | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 17ee148..d8eb4ca 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -689,7 +689,8 @@ ); } }, complete: { value: function(oncomplete) { - return this.then(oncomplete, oncomplete); + oncomplete = oncomplete || function(v) { return v; }; + return this.then(oncomplete, oncomplete); } }, always: { value: function(oncomplete) { this.done(oncomplete, oncomplete); diff --git a/package.json b/package.json index e4682df..341b443 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.33", + "version": "2.0.34", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 981807ded5c3ec02b0679a7528d9f50edfd63ba3 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 19 Nov 2016 13:20:26 +0800 Subject: [PATCH 085/131] Improved thunk & promisify --- lib/common/Future.js | 61 ++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 33 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index d8eb4ca..31e1e0c 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -226,27 +226,36 @@ return isGenerator(constructor.prototype); } + function getThunkCallback(future) { + return function(err, res) { + if (err instanceof Error) { + return future.reject(err); + } + if (arguments.length < 2) { + return future.resolve(err); + } + if (err === null || err === undefined) { + res = slice(arguments, 1); + } + else { + res = slice(arguments, 0); + } + if (res.length == 1) { + future.resolve(res[0]); + } + else { + future.resolve(res); + } + }; + } + function thunkToPromise(fn) { if (isGeneratorFunction(fn) || isGenerator(fn)) { return co(fn); } var thisArg = (function() { return this; })(); var future = new Future(); - fn.call(thisArg, function(err, res) { - if (arguments.length < 2) { - if (err instanceof Error) { - return future.reject(err); - } - return future.resolve(err); - } - if (err) { - return future.reject(err); - } - if (arguments.length > 2) { - res = slice(arguments, 1); - } - future.resolve(res); - }); + fn.call(thisArg, getThunkCallback(future)); return future; } @@ -276,29 +285,15 @@ function promisify(fn) { return function() { var args = slice(arguments, 0); - var results = new Future(); - args.push(function(err, res) { - if (arguments.length < 2) { - if (err instanceof Error) { - return results.reject(err); - } - return results.resolve(err); - } - if (err) { - return results.reject(err); - } - if (arguments.length > 2) { - res = slice(arguments, 1); - } - results.resolve(res); - }); + var future = new Future(); + args.push(getThunkCallback(future)); try { fn.apply(this, args); } catch (err) { - results.reject(err); + future.reject(err); } - return results; + return future; }; } From 5dbea3001f66a95b818d6f11c702ab84ee16a4fb Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 19 Nov 2016 13:28:44 +0800 Subject: [PATCH 086/131] Added co example --- example/co/exam1.js | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 example/co/exam1.js diff --git a/example/co/exam1.js b/example/co/exam1.js new file mode 100644 index 0000000..75dc411 --- /dev/null +++ b/example/co/exam1.js @@ -0,0 +1,7 @@ +var hprose = require('hprose'); + +hprose.co(function*() { + var client = hprose.Client.create('http://hprose.com/example/'); + yield client.useService(); + console.log(yield client.hello("World")); +}); From 57fd730c2ee7b4a61cefb587210e5ad67cedcd7d Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 19 Nov 2016 13:30:42 +0800 Subject: [PATCH 087/131] Update to 2.0.35 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 341b443..2fcb41d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.34", + "version": "2.0.35", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 1e9287f02b8e227b9394aa77ed39a352aad2b335 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 19 Nov 2016 22:27:50 +0800 Subject: [PATCH 088/131] Fixed Client error event --- lib/client/Client.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index 652ff93..a728148 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Nov 14, 2016 * + * LastModified: Nov 19, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -57,6 +57,7 @@ function HproseProxy(setFunction, ns) { function Client(uri, functions, settings) { EventEmitter.call(this); + this.on('error', noop); // private members var _uri, From 161776b9662a5e5a4ca25013d0f2b60644ba633b Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 19 Nov 2016 22:39:30 +0800 Subject: [PATCH 089/131] Added co examples --- example/co/awaitexam2.js | 14 ++++++++++++++ example/co/awaitexam3.js | 37 +++++++++++++++++++++++++++++++++++++ example/co/exam10.js | 19 +++++++++++++++++++ example/co/exam11.js | 11 +++++++++++ example/co/exam12.js | 9 +++++++++ example/co/exam13.js | 7 +++++++ example/co/exam2.js | 16 ++++++++++++++++ example/co/exam3.js | 39 +++++++++++++++++++++++++++++++++++++++ example/co/exam4.js | 16 ++++++++++++++++ example/co/exam5.js | 14 ++++++++++++++ example/co/exam6.js | 12 ++++++++++++ example/co/exam7.js | 18 ++++++++++++++++++ example/co/exam8.js | 22 ++++++++++++++++++++++ example/co/exam9.js | 16 ++++++++++++++++ 14 files changed, 250 insertions(+) create mode 100644 example/co/awaitexam2.js create mode 100644 example/co/awaitexam3.js create mode 100644 example/co/exam10.js create mode 100644 example/co/exam11.js create mode 100644 example/co/exam12.js create mode 100644 example/co/exam13.js create mode 100644 example/co/exam2.js create mode 100644 example/co/exam3.js create mode 100644 example/co/exam4.js create mode 100644 example/co/exam5.js create mode 100644 example/co/exam6.js create mode 100644 example/co/exam7.js create mode 100644 example/co/exam8.js create mode 100644 example/co/exam9.js diff --git a/example/co/awaitexam2.js b/example/co/awaitexam2.js new file mode 100644 index 0000000..9a4bec8 --- /dev/null +++ b/example/co/awaitexam2.js @@ -0,0 +1,14 @@ +(async function() { + try { + console.log(await Promise.resolve("promise")); + console.log(await function *() { return "generator" }); + console.log(await new Date()); + console.log(await 123); + console.log(await 3.14); + console.log(await "hello"); + console.log(await true); + } + catch (e) { + console.error(e); + } +})(); diff --git a/example/co/awaitexam3.js b/example/co/awaitexam3.js new file mode 100644 index 0000000..2890d80 --- /dev/null +++ b/example/co/awaitexam3.js @@ -0,0 +1,37 @@ +(async function() { + try { + var a = []; + for (i = 0; i < 1000000; i++) { + a[i] = i; + } + var start = Date.now(); + await a; + var end = Date.now(); + console.log(end - start); + } + catch (e) { + console.error(e); + } +})(); + +(async function() { + try { + var a = []; + a[0] = a; + console.log(await a); + } + catch (e) { + console.error(e); + } +})(); + +(async function() { + try { + var o = {}; + o.self = o; + console.log(await o); + } + catch (e) { + console.error(e); + } +})(); diff --git a/example/co/exam10.js b/example/co/exam10.js new file mode 100644 index 0000000..b0b19fd --- /dev/null +++ b/example/co/exam10.js @@ -0,0 +1,19 @@ +var hprose = require('hprose'); + + +var coroutine = hprose.wrap(function*(client) { + console.log(1); + console.log((yield client.hello("hprose"))); + var a = client.sum(1, 2, 3); + var b = client.sum(4, 5, 6); + var c = client.sum(7, 8, 9); + console.log((yield client.sum(a, b, c))); + console.log((yield client.hello("world"))); +}); + +hprose.co(function*() { + var client = hprose.Client.create('http://hprose.com/example/'); + yield client.useService(); + coroutine(client); + coroutine(Promise.resolve(client)); +}); diff --git a/example/co/exam11.js b/example/co/exam11.js new file mode 100644 index 0000000..13021d5 --- /dev/null +++ b/example/co/exam11.js @@ -0,0 +1,11 @@ +var hprose = require('hprose'); + +hprose.co(function*() { + var client = hprose.Client.create('http://hprose.com/example/'); + try { + console.log(yield client.invoke('ooxx')); + } + catch (e) { + console.log(e.message); + } +}); \ No newline at end of file diff --git a/example/co/exam12.js b/example/co/exam12.js new file mode 100644 index 0000000..5053384 --- /dev/null +++ b/example/co/exam12.js @@ -0,0 +1,9 @@ +var hprose = require('hprose'); + +hprose.co(function*() { + var client = hprose.Client.create('http://hprose.com/example/'); + console.log(yield client.invoke('oo')); + console.log(yield client.invoke('xx')); +}).catch(function(e) { + console.log(e.message); +}); \ No newline at end of file diff --git a/example/co/exam13.js b/example/co/exam13.js new file mode 100644 index 0000000..265385c --- /dev/null +++ b/example/co/exam13.js @@ -0,0 +1,7 @@ +var hprose = require('hprose'); + +hprose.co(function*() { + var client = hprose.Client.create('http://hprose.com/example/'); + console.log(yield client.invoke('oo').complete()); + console.log(yield client.invoke('xx').complete()); +}); \ No newline at end of file diff --git a/example/co/exam2.js b/example/co/exam2.js new file mode 100644 index 0000000..d3e55ee --- /dev/null +++ b/example/co/exam2.js @@ -0,0 +1,16 @@ +var co = require('hprose').co; + +co(function*() { + try { + console.log(yield Promise.resolve("promise")); + console.log(yield function *() { return "generator" }); + console.log(yield new Date()); + console.log(yield 123); + console.log(yield 3.14); + console.log(yield "hello"); + console.log(yield true); + } + catch (e) { + console.error(e); + } +}); diff --git a/example/co/exam3.js b/example/co/exam3.js new file mode 100644 index 0000000..2fe398d --- /dev/null +++ b/example/co/exam3.js @@ -0,0 +1,39 @@ +var co = require('hprose').co; + +co(function*() { + try { + var a = []; + for (i = 0; i < 1000000; i++) { + a[i] = i; + } + var start = Date.now(); + yield a; + var end = Date.now(); + console.log(end - start); + } + catch (e) { + console.error(e); + } +}); + +co(function*() { + try { + var a = []; + a[0] = a; + console.log(yield a); + } + catch (e) { + console.error(e); + } +}); + +co(function*() { + try { + var o = {}; + o.self = o; + console.log(yield o); + } + catch (e) { + console.error(e); + } +}); diff --git a/example/co/exam4.js b/example/co/exam4.js new file mode 100644 index 0000000..4e5d434 --- /dev/null +++ b/example/co/exam4.js @@ -0,0 +1,16 @@ +var hprose = require("hprose"); +var co = hprose.co; +var thunkify = hprose.thunkify; + +var sum = thunkify(function(a, b, callback) { + console.log("call sum(" + Array.prototype.join.call(arguments) + ")"); + callback(null, a + b); + callback(null, a + b + a); +}); + +co(function*() { + var result = sum(1, 2); + console.log(yield result); + console.log(yield sum(2, 3)); + console.log(yield result); +}); diff --git a/example/co/exam5.js b/example/co/exam5.js new file mode 100644 index 0000000..349bf4e --- /dev/null +++ b/example/co/exam5.js @@ -0,0 +1,14 @@ +var hprose = require("hprose"); +var co = hprose.co; +var thunkify = hprose.thunkify; + +var sum = thunkify(function(a, b, callback) { + callback(a + b); +}); + +co(function*() { + var result = sum(1, 2); + console.log(yield result); + console.log(yield sum(2, 3)); + console.log(yield result); +}); diff --git a/example/co/exam6.js b/example/co/exam6.js new file mode 100644 index 0000000..799b3fe --- /dev/null +++ b/example/co/exam6.js @@ -0,0 +1,12 @@ +var hprose = require('hprose'); + +hprose.co(function*() { + var client = hprose.Client.create('http://hprose.com/example/'); + yield client.useService(); + console.log(yield client.hello("Hprose")); + var a = client.sum(1, 2, 3); + var b = client.sum(4, 5, 6); + var c = client.sum(7, 8, 9); + console.log(yield client.sum(a, b, c)); + console.log(yield client.hello("World")); +}); diff --git a/example/co/exam7.js b/example/co/exam7.js new file mode 100644 index 0000000..440e136 --- /dev/null +++ b/example/co/exam7.js @@ -0,0 +1,18 @@ +var hprose = require('hprose'); + +var client = hprose.Client.create('http://hprose.com/example/'); +var proxy = client.useService(); + +hprose.co(function*() { + var client = yield proxy; + for (var i = 0; i < 5; i++) { + console.log((yield client.hello("1-" + i))); + } +}); + +hprose.co(function*() { + var client = yield proxy; + for (var i = 0; i < 5; i++) { + console.log((yield client.hello("2-" + i))); + } +}); diff --git a/example/co/exam8.js b/example/co/exam8.js new file mode 100644 index 0000000..90fb7cc --- /dev/null +++ b/example/co/exam8.js @@ -0,0 +1,22 @@ +var hprose = require('hprose'); + +function *hello(n, client) { + var result = []; + for (var i = 0; i < 5; i++) { + result[i] = client.hello(n + "-" + i); + } + return Promise.all(result); +} + +hprose.co(function*() { + var client = hprose.Client.create('http://hprose.com/example/'); + yield client.useService(); + var result = yield hprose.co(function *(client) { + var result = []; + for (var i = 0; i < 3; i++) { + result[i] = hprose.co(hello, i, client); + } + return Promise.all(result); + }, client); + console.log(result); +}); diff --git a/example/co/exam9.js b/example/co/exam9.js new file mode 100644 index 0000000..dfa447e --- /dev/null +++ b/example/co/exam9.js @@ -0,0 +1,16 @@ +var hprose = require('hprose'); + +hprose.co(function*() { + var client = hprose.Client.create('http://hprose.com/example/'); + yield client.useService(); + for (var i = 0; i < 5; i++) { + console.log(yield client.hello("1-" + i)); + } + var console_log = hprose.wrap(console.log, console); + for (var i = 0; i < 5; i++) { + console_log(client.hello("2-" + i)); + } + for (var i = 0; i < 5; i++) { + console.log(yield client.hello("3-" + i)); + } +}); From d0d98b85f36054c188cb27d4b5401f603e0ee358 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 19 Nov 2016 22:39:39 +0800 Subject: [PATCH 090/131] Update to 2.0.36 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 2fcb41d..fdc5e7d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.35", + "version": "2.0.36", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From ecf281216fe70a8c8cabba43408005bd99b0bb65 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sat, 19 Nov 2016 22:59:57 +0800 Subject: [PATCH 091/131] Added promisify example --- example/co/exam14.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 example/co/exam14.js diff --git a/example/co/exam14.js b/example/co/exam14.js new file mode 100644 index 0000000..63ad35c --- /dev/null +++ b/example/co/exam14.js @@ -0,0 +1,26 @@ +var hprose = require('hprose'); + +function sum(a, b, callback) { + callback(a + b); +} + +var sum1 = hprose.promisify(sum); +var sum2 = hprose.thunkify(sum); + +sum1(1, 2).then(function(result) { + console.log(result); +}); + +sum2(2, 3)(function(result) { + console.log(result); +}); + +hprose.co(function*() { + console.log(yield sum1(3, 4)); + console.log(yield sum2(4, 5)); +}); + +(async function() { + console.log(await sum1(5, 6)); + console.log(await sum2(6, 7)); +})(); \ No newline at end of file From 53643420b846dfd38544e382cbf83a85e8f2db43 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 23 Nov 2016 16:56:40 +0800 Subject: [PATCH 092/131] Improved co --- lib/common/Future.js | 46 +++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 31e1e0c..538b536 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Nov 18, 2016 * + * LastModified: Nov 23, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -30,8 +30,8 @@ var hasPromise = 'Promise' in global; var setTimeout = global.setTimeout; var clearTimeout = global.clearTimeout; - var foreach = Function.prototype.call.bind(Array.prototype.forEach); - var slice = Function.prototype.call.bind(Array.prototype.slice); + var foreach = Array.prototype.forEach; + var slice = Array.prototype.slice; function Future(computation) { Object.defineProperties(this, { @@ -106,7 +106,7 @@ function arraysize(array) { var size = 0; - foreach(array, function() { ++size; }); + foreach.call(array, function() { ++size; }); return size; } @@ -118,7 +118,7 @@ var result = new Array(n); if (count === 0) { return value(result); } var future = new Future(); - foreach(array, function(element, index) { + foreach.call(array, function(element, index) { toPromise(element).then(function(value) { result[index] = value; if (--count === 0) { @@ -139,7 +139,7 @@ array = isPromise(array) ? array : value(array); return array.then(function(array) { var future = new Future(); - foreach(array, function(element) { + foreach.call(array, function(element) { toPromise(element).fill(future); }); return future; @@ -156,7 +156,7 @@ } var reasons = new Array(n); var future = new Future(); - foreach(array, function(element, index) { + foreach.call(array, function(element, index) { toPromise(element).then(future.resolve, function(e) { reasons[index] = e; if (--count === 0) { @@ -176,7 +176,7 @@ var result = new Array(n); if (count === 0) { return value(result); } var future = new Future(); - foreach(array, function(element, index) { + foreach.call(array, function(element, index) { var f = toPromise(element); f.whenComplete(function() { result[index] = f.inspect(); @@ -191,14 +191,14 @@ function attempt(handler/*, arg1, arg2, ... */) { var thisArg = (function() { return this; })(); - var args = slice(arguments, 1); + var args = slice.call(arguments, 1); return all(args).then(function(args) { return handler.apply(thisArg, args); }); } function run(handler, thisArg/*, arg1, arg2, ... */) { - var args = slice(arguments, 2); + var args = slice.call(arguments, 2); return all(args).then(function(args) { return handler.apply(thisArg, args); }); @@ -235,10 +235,10 @@ return future.resolve(err); } if (err === null || err === undefined) { - res = slice(arguments, 1); + res = slice.call(arguments, 1); } else { - res = slice(arguments, 0); + res = slice.call(arguments, 0); } if (res.length == 1) { future.resolve(res[0]); @@ -261,7 +261,7 @@ function thunkify(fn) { return function() { - var args = slice(arguments, 0); + var args = slice.call(arguments, 0); var thisArg = this; var results = new Future(); args.push(function() { @@ -284,7 +284,7 @@ function promisify(fn) { return function() { - var args = slice(arguments, 0); + var args = slice.call(arguments, 0); var future = new Future(); args.push(getThunkCallback(future)); try { @@ -313,9 +313,14 @@ function co(gen) { var thisArg = (function() { return this; })(); if (typeof gen === 'function') { - var args = slice(arguments, 1); + var args = slice.call(arguments, 1); gen = gen.apply(thisArg, args); } + + if (!gen || typeof gen.next !== 'function') { + return toPromise(gen); + } + var future = new Future(); function onFulfilled(res) { @@ -332,7 +337,7 @@ next(gen['throw'](err)); } catch (e) { - return future.reject(e); + future.reject(e); } } @@ -347,9 +352,6 @@ } } - if (!gen || typeof gen.next !== 'function') { - return future.resolve(gen); - } onFulfilled(); return future; @@ -743,7 +745,7 @@ }); } }, call: { value: function(method) { - var args = slice(arguments, 1); + var args = slice.call(arguments, 1); return this.then(function(result) { return all(args).then(function(args) { return result[method].apply(result, args); @@ -751,7 +753,7 @@ }); } }, bind: { value: function(method) { - var bindargs = slice(arguments); + var bindargs = slice.call(arguments); if (Array.isArray(method)) { for (var i = 0, n = method.length; i < n; ++i) { bindargs[0] = method[i]; @@ -762,7 +764,7 @@ bindargs.shift(); var self = this; Object.defineProperty(this, method, { value: function() { - var args = slice(arguments); + var args = slice.call(arguments); return self.then(function(result) { return all(bindargs.concat(args)).then(function(args) { return result[method].apply(result, args); From e814e86e49d4e6dd1b981bbd47dd8b4a63da9068 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 24 Nov 2016 23:13:49 +0800 Subject: [PATCH 093/131] Improved Future --- lib/common/Future.js | 74 +++++++++++++++++--------------------------- 1 file changed, 28 insertions(+), 46 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 538b536..3ac4cbc 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Nov 23, 2016 * + * LastModified: Nov 24, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -34,12 +34,12 @@ var slice = Array.prototype.slice; function Future(computation) { + var self = this; Object.defineProperties(this, { _subscribers: { value: [] }, resolve: { value: this.resolve.bind(this) }, reject: { value: this.reject.bind(this) } }); - var self = this; if (typeof computation === 'function') { process.nextTick(function() { try { @@ -56,14 +56,18 @@ return obj instanceof Future; } + function toFuture(obj) { + return isFuture(obj) ? obj : value(obj); + } + function isPromise(obj) { return 'function' === typeof obj.then; } function delayed(duration, value) { var computation = (typeof value === 'function') ? - value : - function() { return value; }; + value : + function() { return value; }; var future = new Future(); setTimeout(function() { try { @@ -111,15 +115,14 @@ } function all(array) { - array = isPromise(array) ? array : value(array); - return array.then(function(array) { + return toFuture(array).then(function(array) { var n = array.length; var count = arraysize(array); var result = new Array(n); - if (count === 0) { return value(result); } + if (count === 0) { return result; } var future = new Future(); foreach.call(array, function(element, index) { - toPromise(element).then(function(value) { + toFuture(element).then(function(value) { result[index] = value; if (--count === 0) { future.resolve(result); @@ -136,19 +139,17 @@ } function race(array) { - array = isPromise(array) ? array : value(array); - return array.then(function(array) { + return toFuture(array).then(function(array) { var future = new Future(); foreach.call(array, function(element) { - toPromise(element).fill(future); + toFuture(element).fill(future); }); return future; }); } function any(array) { - array = isPromise(array) ? array : value(array); - return array.then(function(array) { + return toFuture(array).then(function(array) { var n = array.length; var count = arraysize(array); if (count === 0) { @@ -157,7 +158,7 @@ var reasons = new Array(n); var future = new Future(); foreach.call(array, function(element, index) { - toPromise(element).then(future.resolve, function(e) { + toFuture(element).then(future.resolve, function(e) { reasons[index] = e; if (--count === 0) { future.reject(reasons); @@ -169,16 +170,15 @@ } function settle(array) { - array = isPromise(array) ? array : value(array); - return array.then(function(array) { + return toFuture(array).then(function(array) { var n = array.length; var count = arraysize(array); var result = new Array(n); - if (count === 0) { return value(result); } + if (count === 0) { return result; } var future = new Future(); foreach.call(array, function(element, index) { - var f = toPromise(element); - f.whenComplete(function() { + var f = toFuture(element); + f.complete(function() { result[index] = f.inspect(); if (--count === 0) { future.resolve(result); @@ -298,16 +298,10 @@ } function toPromise(obj) { - if (!obj) { - return value(obj); - } - if (isPromise(obj)) { - return obj; - } if (isGeneratorFunction(obj) || isGenerator(obj)) { return co(obj); } - return value(obj); + return toFuture(obj); } function co(gen) { @@ -370,6 +364,8 @@ }; } + co.wrap = wrap; + function forEach(array, callback, thisArg) { thisArg = thisArg || (function() { return this; })(); return all(array).then(function(array) { @@ -408,10 +404,7 @@ function reduce(array, callback, initialValue) { if (arguments.length > 2) { return all(array).then(function(array) { - if (!isPromise(initialValue)) { - initialValue = value(initialValue); - } - return initialValue.then(function(value) { + return toFuture(initialValue).then(function(value) { return array.reduce(callback, value); }); }); @@ -424,10 +417,7 @@ function reduceRight(array, callback, initialValue) { if (arguments.length > 2) { return all(array).then(function(array) { - if (!isPromise(initialValue)) { - initialValue = value(initialValue); - } - return initialValue.then(function(value) { + return toFuture(initialValue).then(function(value) { return array.reduceRight(callback, value); }); }); @@ -439,10 +429,7 @@ function indexOf(array, searchElement, fromIndex) { return all(array).then(function(array) { - if (!isPromise(searchElement)) { - searchElement = value(searchElement); - } - return searchElement.then(function(searchElement) { + return toFuture(searchElement).then(function(searchElement) { return array.indexOf(searchElement, fromIndex); }); }); @@ -450,10 +437,7 @@ function lastIndexOf(array, searchElement, fromIndex) { return all(array).then(function(array) { - if (!isPromise(searchElement)) { - searchElement = value(searchElement); - } - return searchElement.then(function(searchElement) { + return toFuture(searchElement).then(function(searchElement) { if (fromIndex === undefined) { fromIndex = array.length - 1; } @@ -464,10 +448,7 @@ function includes(array, searchElement, fromIndex) { return all(array).then(function(array) { - if (!isPromise(searchElement)) { - searchElement = value(searchElement); - } - return searchElement.then(function(searchElement) { + return toFuture(searchElement).then(function(searchElement) { return array.includes(searchElement, fromIndex); }); }); @@ -501,6 +482,7 @@ // extended methods promise: { value: promise }, isFuture: { value: isFuture }, + toFuture: { value: toFuture }, isPromise: { value: isPromise }, toPromise: { value: toPromise }, join: { value: join }, From b3d094723a22befc7bcbf7567646e12c74aab2e0 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 24 Nov 2016 23:33:37 +0800 Subject: [PATCH 094/131] Update to v2.0.37 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index fdc5e7d..5b1645c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.36", + "version": "2.0.37", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 4dfc5330631bb3bf4732fec6b41be41023d7bdf9 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 2 Dec 2016 16:28:59 +0800 Subject: [PATCH 095/131] Added httpHeader support for http client --- lib/client/HttpClient.js | 28 +++++++++++++++++++++++----- package.json | 2 +- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/lib/client/HttpClient.js b/lib/client/HttpClient.js index dc36ba8..ec0e08e 100644 --- a/lib/client/HttpClient.js +++ b/lib/client/HttpClient.js @@ -13,7 +13,7 @@ * * * Hprose Http Client for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Dec 2, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -125,6 +125,26 @@ function HttpClient(uri, functions, settings) { var self = this; + function getRequestHeader(headers) { + var header = {}; + var name, value; + for (name in _header) { + header[name] = _header[name]; + } + if (headers) { + for (name in headers) { + value = headers[name]; + if (Array.isArray(value)) { + header[name] = value.join(', '); + } + else { + header[name] = value; + } + } + } + return header; + } + function send(request, future) { request = BytesIO.toBuffer(request); var options = parse(self.uri); @@ -147,16 +167,14 @@ function HttpClient(uri, functions, settings) { options[key] = self.options[key]; } options.method = 'POST'; - options.headers = Object.create(null); - for (var name in _header) { - options.headers[name] = _header[name]; - } + options.headers = getRequestHeader(context.httpHeader); options.headers['Content-Length'] = request.length; var cookie = getCookie(options.host, options.path, secure); if (cookie !== '') { options.headers.Cookie = cookie; } var req = client.request(options, function(resp) { + context.httpHeader = resp.headers; var bytes = new BytesIO(); resp.on('data', function(data) { bytes.write(data); }); resp.on('end', function() { diff --git a/package.json b/package.json index 5b1645c..a979d91 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.37", + "version": "2.0.38", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 08e288c3908620e6b6a7ee9fe30a120fa8485e48 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 2 Dec 2016 22:03:14 +0800 Subject: [PATCH 096/131] Renamed env to context --- lib/client/HttpClient.js | 10 +++++----- lib/client/SocketClient.js | 34 +++++++++++++++++----------------- lib/client/WebSocketClient.js | 10 +++++----- 3 files changed, 27 insertions(+), 27 deletions(-) diff --git a/lib/client/HttpClient.js b/lib/client/HttpClient.js index ec0e08e..3174b68 100644 --- a/lib/client/HttpClient.js +++ b/lib/client/HttpClient.js @@ -145,7 +145,7 @@ function HttpClient(uri, functions, settings) { return header; } - function send(request, future) { + function send(request, future, context) { request = BytesIO.toBuffer(request); var options = parse(self.uri); var protocol = options.protocol; @@ -195,11 +195,11 @@ function HttpClient(uri, functions, settings) { return req; } - function sendAndReceive(request, env) { + function sendAndReceive(request, context) { var future = new Future(); var req = send(request, future); - if (env.timeout > 0) { - future = future.timeout(env.timeout).catchError(function(e) { + if (context.timeout > 0) { + future = future.timeout(context.timeout).catchError(function(e) { req.removeAllListeners('error'); req.on('error', noop); req.abort(); @@ -209,7 +209,7 @@ function HttpClient(uri, functions, settings) { return e instanceof TimeoutError; }); } - if (env.oneway) { future.resolve(); } + if (context.oneway) { future.resolve(); } return future; } diff --git a/lib/client/SocketClient.js b/lib/client/SocketClient.js index 0b79037..5a9a9d8 100644 --- a/lib/client/SocketClient.js +++ b/lib/client/SocketClient.js @@ -13,7 +13,7 @@ * * * Hprose Socket Client for Node.js. * * * - * LastModified: Sep 17, 2016 * + * LastModified: Dec 2, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -203,10 +203,10 @@ FullDuplexSocketTransporter.prototype = Object.create( } } } }, - send: { value: function(request, future, id, env, conn) { + send: { value: function(request, future, id, context, conn) { var self = this; - var timeout = env.timeout; + var timeout = context.timeout; if (timeout > 0) { conn.timeoutIds[id] = global.setTimeout(function() { self.clean(conn, id); @@ -233,11 +233,11 @@ FullDuplexSocketTransporter.prototype = Object.create( getNextId: { value: function() { return (this.nextid < 0x7fffffff) ? ++this.nextid : this.nextid = 0; } }, - sendAndReceive: { value: function(request, future, env) { + sendAndReceive: { value: function(request, future, context) { var conn = this.fetch(); var id = this.getNextId(); if (conn) { - this.send(request, future, id, env, conn); + this.send(request, future, id, context, conn); } else if (this.size < this.client.maxPoolSize) { conn = this.create(); @@ -250,11 +250,11 @@ FullDuplexSocketTransporter.prototype = Object.create( conn.removeAllListeners('error'); conn.connected = true; self.init(conn); - self.send(request, future, id, env, conn); + self.send(request, future, id, context, conn); }); } else { - this.requests.push([request, future, id, env]); + this.requests.push([request, future, id, context]); } } } }); @@ -307,9 +307,9 @@ HalfDuplexSocketTransporter.prototype = Object.create( this.recycle(conn); } } }, - send: { value: function(request, future, env, conn) { + send: { value: function(request, future, context, conn) { var self = this; - var timeout = env.timeout; + var timeout = context.timeout; if (timeout > 0) { conn.timeoutId = global.setTimeout(function() { self.clean(conn); @@ -337,10 +337,10 @@ HalfDuplexSocketTransporter.prototype = Object.create( } conn.write(buf); } }, - sendAndReceive: { value: function(request, future, env) { + sendAndReceive: { value: function(request, future, context) { var conn = this.fetch(); if (conn) { - this.send(request, future, env, conn); + this.send(request, future, context, conn); } else if (this.size < this.client.maxPoolSize) { conn = this.create(); @@ -352,11 +352,11 @@ HalfDuplexSocketTransporter.prototype = Object.create( conn.once('connect', function() { conn.removeAllListeners('error'); conn.connected = true; - self.send(request, future, env, conn); + self.send(request, future, context, conn); }); } else { - this.requests.push([request, future, env]); + this.requests.push([request, future, context]); } } } }); @@ -422,21 +422,21 @@ function SocketClient(uri, functions, settings) { } } - function sendAndReceive(request, env) { + function sendAndReceive(request, context) { var future = new Future(); if (_fullDuplex) { if ((fdtrans === null) || (fdtrans.uri !== self.uri)) { fdtrans = new FullDuplexSocketTransporter(self); } - fdtrans.sendAndReceive(request, future, env); + fdtrans.sendAndReceive(request, future, context); } else { if ((hdtrans === null) || (hdtrans.uri !== self.uri)) { hdtrans = new HalfDuplexSocketTransporter(self); } - hdtrans.sendAndReceive(request, future, env); + hdtrans.sendAndReceive(request, future, context); } - if (env.oneway) { future.resolve(); } + if (context.oneway) { future.resolve(); } return future; } diff --git a/lib/client/WebSocketClient.js b/lib/client/WebSocketClient.js index 6218789..98451a0 100644 --- a/lib/client/WebSocketClient.js +++ b/lib/client/WebSocketClient.js @@ -12,7 +12,7 @@ * * * Hprose WebSocket Client for HTML5. * * * - * LastModified: Nov 18, 2016 * + * LastModified: Dec 2, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -107,12 +107,12 @@ function WebSocketClient(uri, functions, settings) { ws.on('error', onerror); ws.on('close', onclose); } - function sendAndReceive(request, env) { + function sendAndReceive(request, context) { var id = getNextId(); var future = new Future(); _futures[id] = future; - if (env.timeout > 0) { - future = future.timeout(env.timeout).catchError(function(e) { + if (context.timeout > 0) { + future = future.timeout(context.timeout).catchError(function(e) { delete _futures[id]; --_count; throw e; @@ -133,7 +133,7 @@ function WebSocketClient(uri, functions, settings) { else { _requests.push([id, request]); } - if (env.oneway) { future.resolve(); } + if (context.oneway) { future.resolve(); } return future; } function close() { From b81b868ae1280e55e8b2dbf2fd34af67abcf76ee Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Fri, 2 Dec 2016 22:31:32 +0800 Subject: [PATCH 097/131] Improved getRequestHeader --- lib/client/HttpClient.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/client/HttpClient.js b/lib/client/HttpClient.js index 3174b68..a60a4fc 100644 --- a/lib/client/HttpClient.js +++ b/lib/client/HttpClient.js @@ -126,7 +126,7 @@ function HttpClient(uri, functions, settings) { var self = this; function getRequestHeader(headers) { - var header = {}; + var header = Object.create(null); var name, value; for (name in _header) { header[name] = _header[name]; From 43226d80b6af2b66fcfe315ed70f65d8f9a73165 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 4 Dec 2016 19:50:32 +0800 Subject: [PATCH 098/131] Fixed HttpClient --- lib/client/HttpClient.js | 4 ++-- package.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/client/HttpClient.js b/lib/client/HttpClient.js index a60a4fc..84c6f68 100644 --- a/lib/client/HttpClient.js +++ b/lib/client/HttpClient.js @@ -13,7 +13,7 @@ * * * Hprose Http Client for Node.js. * * * - * LastModified: Dec 2, 2016 * + * LastModified: Dec 4, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -197,7 +197,7 @@ function HttpClient(uri, functions, settings) { function sendAndReceive(request, context) { var future = new Future(); - var req = send(request, future); + var req = send(request, future, context); if (context.timeout > 0) { future = future.timeout(context.timeout).catchError(function(e) { req.removeAllListeners('error'); diff --git a/package.json b/package.json index a979d91..15f641e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.38", + "version": "2.0.39", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 793c2664e1ad9ea378d0c986b134520d4d0b8d04 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 5 Dec 2016 01:22:32 +0800 Subject: [PATCH 099/131] Added coroutine middleware and service support. --- example/httpclient.js | 19 +++++++++++++++++ example/httpserver.js | 21 +++++++++++++++++++ .../middleware/batchlog/batchloghandler.js | 8 +++---- example/middleware/batchlog/loghandler.js | 8 +++---- example/middleware/cache/loghandler.js | 8 +++---- .../middleware/compressCache/sizehandler.js | 8 +++---- .../middleware/compressCache/stathandler.js | 10 ++++----- example/middleware/log/loghandler.js | 8 +++++++ example/middleware/log2/loghandler.js | 8 +++---- lib/client/Client.js | 16 ++++---------- lib/server/Service.js | 20 +++++++----------- package.json | 2 +- 12 files changed, 79 insertions(+), 57 deletions(-) create mode 100644 example/httpclient.js create mode 100644 example/httpserver.js diff --git a/example/httpclient.js b/example/httpclient.js new file mode 100644 index 0000000..a0e0628 --- /dev/null +++ b/example/httpclient.js @@ -0,0 +1,19 @@ +/*jshint node:true, eqeqeq:true */ +'use strict'; + +var hprose = require('../lib/hprose.js'); +var client = hprose.Client.create('http://127.0.0.1:8080/', []); +client.simple = true; +client.on('error', function(func, e) { + console.log(func, e); +}); +hprose.co(function*() { + var proxy = client.useService(['hello']); + var start = new Date().getTime(); + for (var i = 0; i < 100; i++) { + var result = yield proxy.hello(i); + console.log(result); + } + var end = new Date().getTime(); + console.log("time: " + (end - start)); +}); diff --git a/example/httpserver.js b/example/httpserver.js new file mode 100644 index 0000000..6e11757 --- /dev/null +++ b/example/httpserver.js @@ -0,0 +1,21 @@ +/*jshint node:true, eqeqeq:true */ +'use strict'; + +var hprose = require('../lib/hprose.js'); + +function* hello(name) { + return 'Hello ' + name + '!'; +} + +var server = hprose.Server.create("http://0.0.0.0:8080/"); +server.crossDomain = true; +server.crossDomainXmlFile = './crossdomain.xml'; +server.debug = true; +server.addFunction(hello); +server.on('sendError', function(message) { + console.log(message.stack); +}); +process.on('SIGINT', function() { + server.stop(); +}); +server.start(); diff --git a/example/middleware/batchlog/batchloghandler.js b/example/middleware/batchlog/batchloghandler.js index 9218024..c2e5764 100644 --- a/example/middleware/batchlog/batchloghandler.js +++ b/example/middleware/batchlog/batchloghandler.js @@ -1,8 +1,6 @@ -module.exports = function(batches, context, next) { +module.exports = function*(batches, context, next) { console.log("before invoke:", batches); - var result = next(batches, context); - result.then(function(result) { - console.log("after invoke:", batches, result); - }); + var result = yield next(batches, context); + console.log("after invoke:", batches, result); return result; }; diff --git a/example/middleware/batchlog/loghandler.js b/example/middleware/batchlog/loghandler.js index c77a599..02f301f 100644 --- a/example/middleware/batchlog/loghandler.js +++ b/example/middleware/batchlog/loghandler.js @@ -1,8 +1,6 @@ -module.exports = function(name, args, context, next) { +module.exports = function*(name, args, context, next) { console.log("before invoke:", name, args); - var result = next(name, args, context); - result.then(function(result) { - console.log("after invoke:", name, args, result); - }); + var result = yield next(name, args, context); + console.log("after invoke:", name, args, result); return result; }; diff --git a/example/middleware/cache/loghandler.js b/example/middleware/cache/loghandler.js index c77a599..02f301f 100644 --- a/example/middleware/cache/loghandler.js +++ b/example/middleware/cache/loghandler.js @@ -1,8 +1,6 @@ -module.exports = function(name, args, context, next) { +module.exports = function*(name, args, context, next) { console.log("before invoke:", name, args); - var result = next(name, args, context); - result.then(function(result) { - console.log("after invoke:", name, args, result); - }); + var result = yield next(name, args, context); + console.log("after invoke:", name, args, result); return result; }; diff --git a/example/middleware/compressCache/sizehandler.js b/example/middleware/compressCache/sizehandler.js index b1fe00c..4c6e419 100644 --- a/example/middleware/compressCache/sizehandler.js +++ b/example/middleware/compressCache/sizehandler.js @@ -1,11 +1,9 @@ var hprose = require('hprose'); module.exports = function(message) { - return function(request, context, next) { + return function*(request, context, next) { console.log(message + ' request size: ' + request.length); - var response = next(request, context); - response.then(function(data) { - console.log(message + ' response size: ' + data.length); - }); + var response = yield next(request, context); + console.log(message + ' response size: ' + response.length); return response; }; }; diff --git a/example/middleware/compressCache/stathandler.js b/example/middleware/compressCache/stathandler.js index 8b5e170..ac84f64 100644 --- a/example/middleware/compressCache/stathandler.js +++ b/example/middleware/compressCache/stathandler.js @@ -1,11 +1,9 @@ module.exports = function(message) { - return function(request, context, next) { + return function*(request, context, next) { var start = Date.now(); - var response = next(request, context); - response.then(function() { - var end = Date.now(); - console.log(message + ': It takes ' + (end - start) + ' ms.'); - }); + var response = yield next(request, context); + var end = Date.now(); + console.log(message + ': It takes ' + (end - start) + ' ms.'); return response; }; }; diff --git a/example/middleware/log/loghandler.js b/example/middleware/log/loghandler.js index c77a599..d637f41 100644 --- a/example/middleware/log/loghandler.js +++ b/example/middleware/log/loghandler.js @@ -1,3 +1,4 @@ +/* module.exports = function(name, args, context, next) { console.log("before invoke:", name, args); var result = next(name, args, context); @@ -6,3 +7,10 @@ module.exports = function(name, args, context, next) { }); return result; }; +*/ +module.exports = function*(name, args, context, next) { + console.log("before invoke:", name, args); + var result = yield next(name, args, context); + console.log("after invoke:", name, args, result); + return result; +}; diff --git a/example/middleware/log2/loghandler.js b/example/middleware/log2/loghandler.js index d26af91..d182824 100644 --- a/example/middleware/log2/loghandler.js +++ b/example/middleware/log2/loghandler.js @@ -1,9 +1,7 @@ var hprose = require('hprose'); -module.exports = function(request, context, next) { +module.exports = function*(request, context, next) { console.log(hprose.BytesIO.toString(request)); - var response = next(request, context); - response.then(function(data) { - console.log(hprose.BytesIO.toString(data)); - }); + var response = yield next(request, context); + console.log(hprose.BytesIO.toString(response)); return response; }; diff --git a/lib/client/Client.js b/lib/client/Client.js index a728148..2b95efd 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -1086,9 +1086,7 @@ function Client(uri, functions, settings) { _invokeHandler = _invokeHandlers.reduceRight( function(next, handler) { return function(name, args, context) { - return Future.sync(function() { - return handler(name, args, context, next); - }); + return Future.toPromise(handler(name, args, context, next)); }; }, invokeHandler); } @@ -1097,9 +1095,7 @@ function Client(uri, functions, settings) { _batchInvokeHandler = _batchInvokeHandlers.reduceRight( function(next, handler) { return function(batches, context) { - return Future.sync(function() { - return handler(batches, context, next); - }); + return Future.toPromise(handler(batches, context, next)); }; }, batchInvokeHandler); } @@ -1108,9 +1104,7 @@ function Client(uri, functions, settings) { _beforeFilterHandler = _beforeFilterHandlers.reduceRight( function(next, handler) { return function(request, context) { - return Future.sync(function() { - return handler(request, context, next); - }); + return Future.toPromise(handler(request, context, next)); }; }, beforeFilterHandler); } @@ -1119,9 +1113,7 @@ function Client(uri, functions, settings) { _afterFilterHandler = _afterFilterHandlers.reduceRight( function(next, handler) { return function(request, context) { - return Future.sync(function() { - return handler(request, context, next); - }); + return Future.toPromise(handler(request, context, next)); }; }, afterFilterHandler); } diff --git a/lib/server/Service.js b/lib/server/Service.js index 74795fd..3e75633 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Oct 16, 2016 * + * LastModified: Dec 5, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -37,7 +37,7 @@ function callService(args, context) { if (context.oneway) { process.nextTick(function() { try { - context.method.apply(context.scope, args); + Future.toPromise(context.method.apply(context.scope, args)); } catch (e) {} }); @@ -46,12 +46,12 @@ function callService(args, context) { } return null; } - return context.method.apply(context.scope, args); + return Future.toPromise(context.method.apply(context.scope, args)); } function getFuncName(func, obj) { var f = func.toString(); - var funcname = f.substr(0, f.indexOf('(')).replace(/(^\s*function\s*)|(\s*$)/ig, ''); + var funcname = f.substr(0, f.indexOf('(')).replace(/(^\s*function\*?\s*)|(\s*$)/ig, ''); if ((funcname === '') && obj) { for (var name in obj) { if (obj[name] === func) { return name; } @@ -1113,9 +1113,7 @@ function Service() { _beforeFilterHandler = _beforeFilterHandlers.reduceRight( function(next, handler) { return function(request, context) { - return Future.sync(function() { - return handler(request, context, next); - }); + return Future.toPromise(handler(request, context, next)); }; }, beforeFilterHandler); } @@ -1124,9 +1122,7 @@ function Service() { _afterFilterHandler = _afterFilterHandlers.reduceRight( function(next, handler) { return function(request, context) { - return Future.sync(function() { - return handler(request, context, next); - }); + return Future.toPromise(handler(request, context, next)); }; }, afterFilterHandler); } @@ -1135,9 +1131,7 @@ function Service() { _invokeHandler = _invokeHandlers.reduceRight( function(next, handler) { return function(name, args, context) { - return Future.sync(function() { - return handler(name, args, context, next); - }); + return Future.toPromise(handler(name, args, context, next)); }; }, invokeHandler); } diff --git a/package.json b/package.json index 15f641e..6c58b65 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.39", + "version": "2.0.40", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 32092aa04bf1c8be5c2bbdef1cb214612a96fe98 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 5 Dec 2016 02:36:12 +0800 Subject: [PATCH 100/131] Added toPromise example --- example/co/exam15.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 example/co/exam15.js diff --git a/example/co/exam15.js b/example/co/exam15.js new file mode 100644 index 0000000..02bd3dc --- /dev/null +++ b/example/co/exam15.js @@ -0,0 +1,27 @@ +var hprose = require('hprose'); + +function normal(p) { + console.log(p); + return normal; +} + +function* coroutine(p) { + console.log(yield p); + return coroutine; +} + +// hprose.co(function*() { +// var p = Promise.resolve(123); +// console.log(normal(p)); +// console.log(yield coroutine(p)); +// }) + +function* run(fn) { + var p = Promise.resolve(123); + console.log(yield hprose.Future.toPromise(fn(p))); +} + +hprose.co(function*() { + yield run(normal); + yield run(coroutine); +}); \ No newline at end of file From 0470c8c97127761c92524f2d4d6ea3f2b853e451 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 5 Dec 2016 13:04:01 +0800 Subject: [PATCH 101/131] Improved co --- lib/common/Future.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/common/Future.js b/lib/common/Future.js index 3ac4cbc..7176bde 100644 --- a/lib/common/Future.js +++ b/lib/common/Future.js @@ -13,7 +13,7 @@ * * * Hprose Future for Node.js. * * * - * LastModified: Nov 24, 2016 * + * LastModified: Dec 5, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -312,7 +312,7 @@ } if (!gen || typeof gen.next !== 'function') { - return toPromise(gen); + return toFuture(gen); } var future = new Future(); From 43dada43c1f0f0c3d65b4ae5a5136dc1fde5bbaf Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 11 Dec 2016 21:30:53 +0800 Subject: [PATCH 102/131] Update README --- README.md | 6 +++--- README_zh_CN.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 714aaf1..1bdef39 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ +

Hprose

+ Promises/A+ logo - - - + # Hprose for Node.js [![Join the chat at https://gitter.im/hprose/hprose-nodejs](https://img.shields.io/badge/GITTER-join%20chat-green.svg)](https://gitter.im/hprose/hprose-nodejs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) diff --git a/README_zh_CN.md b/README_zh_CN.md index 54c1510..cf30d96 100644 --- a/README_zh_CN.md +++ b/README_zh_CN.md @@ -1,10 +1,10 @@ +

Hprose

+ Promises/A+ logo - - - + # Hprose for Node.js [![Join the chat at https://gitter.im/hprose/hprose-nodejs](https://img.shields.io/badge/GITTER-join%20chat-green.svg)](https://gitter.im/hprose/hprose-nodejs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) From 0202a9b9d4a6900c765fca8dd3bb93e15fc97fdb Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 11 Dec 2016 22:08:33 +0800 Subject: [PATCH 103/131] Update README --- README.md | 3 +-- README_zh_CN.md | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1bdef39..de20967 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,7 @@

Hprose

- Promises/A+ logo + Promises/A+ logo # Hprose for Node.js diff --git a/README_zh_CN.md b/README_zh_CN.md index cf30d96..ba57de0 100644 --- a/README_zh_CN.md +++ b/README_zh_CN.md @@ -1,8 +1,7 @@

Hprose

- Promises/A+ logo + Promises/A+ logo # Hprose for Node.js From 4974820283da70f950cff5046c1eff4545ec402d Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Mon, 13 Feb 2017 15:06:22 +0800 Subject: [PATCH 104/131] if object has no constructor, return 'Object' --- lib/io/Writer.js | 5 ++++- package.json | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/io/Writer.js b/lib/io/Writer.js index c92b3bf..b881e7c 100644 --- a/lib/io/Writer.js +++ b/lib/io/Writer.js @@ -13,7 +13,7 @@ * * * Hprose Writer for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Feb 13, 2017 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -27,6 +27,9 @@ var ClassManager = global.hprose.ClassManager; function getClassName(obj) { var cls = obj.constructor; + if (!cls) { + return 'Object'; + } var classname = ClassManager.getClassAlias(cls); if (classname) { return classname; } if (cls.name) { diff --git a/package.json b/package.json index 6c58b65..a84a864 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.40", + "version": "2.0.41", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From b60ce73d54158231f16fab1f4e99cabd374249da Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Tue, 14 Feb 2017 19:42:59 +0800 Subject: [PATCH 105/131] Fixed method name --- lib/client/Client.js | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index 2b95efd..7460745 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -243,7 +243,7 @@ function Client(uri, functions, settings) { } else { for (var n in m) { - setMethods(stub, obj[name], name + '_', n, m[n]); + setMethods(stub, obj[name], namespace + name + '_', n, m[n]); } } } diff --git a/package.json b/package.json index a84a864..aa0a5c9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.41", + "version": "2.0.42", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From f06e2903d3d3b83192d4b5b3b5a5d87257ff2d9d Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Tue, 14 Feb 2017 19:48:25 +0800 Subject: [PATCH 106/131] Update ws dependence --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index aa0a5c9..400907d 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "lib": "lib/" }, "main": "lib/hprose.js", - "optionalDependencies": { "ws": "~1.1.1" }, + "optionalDependencies": { "ws": "~2.0.3" }, "devDependencies": { "promises-aplus-tests": "*" }, From 53c319621d44a076be2f7e09af4c51a6a58cf6d8 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Thu, 4 May 2017 14:38:24 +0800 Subject: [PATCH 107/131] Update to 2.0.43 --- lib/client/WebSocketClient.js | 1 + package.json | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/client/WebSocketClient.js b/lib/client/WebSocketClient.js index 98451a0..a39195d 100644 --- a/lib/client/WebSocketClient.js +++ b/lib/client/WebSocketClient.js @@ -113,6 +113,7 @@ function WebSocketClient(uri, functions, settings) { _futures[id] = future; if (context.timeout > 0) { future = future.timeout(context.timeout).catchError(function(e) { + ws = null; delete _futures[id]; --_count; throw e; diff --git a/package.json b/package.json index 400907d..29d27ec 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.42", + "version": "2.0.43", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ @@ -50,7 +50,7 @@ "lib": "lib/" }, "main": "lib/hprose.js", - "optionalDependencies": { "ws": "~2.0.3" }, + "optionalDependencies": { "ws": "~2.3.1" }, "devDependencies": { "promises-aplus-tests": "*" }, From eae8d7c216603bcb61a2ec92014e3a34ff708a94 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 28 Jun 2017 09:57:39 +0800 Subject: [PATCH 108/131] detect and close broken connections --- lib/server/WebSocketServer.js | 19 ++++++++++++++++++- lib/server/WebSocketService.js | 6 +++++- package.json | 2 +- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/lib/server/WebSocketServer.js b/lib/server/WebSocketServer.js index 4513e32..6efacfc 100644 --- a/lib/server/WebSocketServer.js +++ b/lib/server/WebSocketServer.js @@ -13,7 +13,7 @@ * * * Hprose WebSocket Server for Node.js. * * * - * LastModified: Aug 20, 2016 * + * LastModified: Jun 28, 2017 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -40,6 +40,7 @@ function WebSocketServer(options, tlsOptions, handler) { options.server = httpserver; options.perMessageDeflate = false; var server = null; + var interval = null; function onerror(e, socket) { var context = { @@ -58,14 +59,26 @@ function WebSocketServer(options, tlsOptions, handler) { } httpserver.on('clientError', onerror); + + function ping() { + server.clients.forEach(function each(ws) { + if (ws.isAlive === false) return ws.terminate(); + ws.ping('', false, true); + ws.isAlive = false; + }); + } function start() { httpserver.listen(port, host); server = new ws.Server(options); server.on('connection', self.wsHandle); server.on('error', onerror); + interval = setInterval(ping, 30000); } function stop() { + if (interval !== null) { + clearInterval(interval); + } server.close(); httpserver.close(); } @@ -74,8 +87,12 @@ function WebSocketServer(options, tlsOptions, handler) { server = new ws.Server(options); server.on('connection', self.wsHandle); server.on('error', onerror); + interval = setInterval(ping, 30000); } function close(callback) { + if (interval !== null) { + clearInterval(interval); + } server.close(); httpserver.close(callback); } diff --git a/lib/server/WebSocketService.js b/lib/server/WebSocketService.js index 0779cee..0332585 100644 --- a/lib/server/WebSocketService.js +++ b/lib/server/WebSocketService.js @@ -13,7 +13,7 @@ * * * Hprose WebSocket Service for Node.js. * * * - * LastModified: Sep 30, 2016 * + * LastModified: Jun 28, 2017 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -105,6 +105,10 @@ function WebSocketService() { ws.close(); return; } + ws.isAlive = true; + ws.on('pong', function() { + ws.isAlive = true; + }); ws.on('close', function() { try { self.emit('close',context); diff --git a/package.json b/package.json index 29d27ec..5114259 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "lib": "lib/" }, "main": "lib/hprose.js", - "optionalDependencies": { "ws": "~2.3.1" }, + "optionalDependencies": { "ws": "~3.0.0" }, "devDependencies": { "promises-aplus-tests": "*" }, From f297c9aefd7f00a1467781a05c4d3e0f8d98a429 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 28 Jun 2017 09:59:50 +0800 Subject: [PATCH 109/131] Update to 2.0.44 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 5114259..39eedc2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.43", + "version": "2.0.44", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 8b3e984faa17d720ff015a130da23a8403546239 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 28 Jun 2017 10:35:35 +0800 Subject: [PATCH 110/131] Revert "detect and close broken connections" This reverts commit eae8d7c216603bcb61a2ec92014e3a34ff708a94. --- lib/server/WebSocketServer.js | 19 +------------------ lib/server/WebSocketService.js | 6 +----- package.json | 2 +- 3 files changed, 3 insertions(+), 24 deletions(-) diff --git a/lib/server/WebSocketServer.js b/lib/server/WebSocketServer.js index 6efacfc..4513e32 100644 --- a/lib/server/WebSocketServer.js +++ b/lib/server/WebSocketServer.js @@ -13,7 +13,7 @@ * * * Hprose WebSocket Server for Node.js. * * * - * LastModified: Jun 28, 2017 * + * LastModified: Aug 20, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -40,7 +40,6 @@ function WebSocketServer(options, tlsOptions, handler) { options.server = httpserver; options.perMessageDeflate = false; var server = null; - var interval = null; function onerror(e, socket) { var context = { @@ -59,26 +58,14 @@ function WebSocketServer(options, tlsOptions, handler) { } httpserver.on('clientError', onerror); - - function ping() { - server.clients.forEach(function each(ws) { - if (ws.isAlive === false) return ws.terminate(); - ws.ping('', false, true); - ws.isAlive = false; - }); - } function start() { httpserver.listen(port, host); server = new ws.Server(options); server.on('connection', self.wsHandle); server.on('error', onerror); - interval = setInterval(ping, 30000); } function stop() { - if (interval !== null) { - clearInterval(interval); - } server.close(); httpserver.close(); } @@ -87,12 +74,8 @@ function WebSocketServer(options, tlsOptions, handler) { server = new ws.Server(options); server.on('connection', self.wsHandle); server.on('error', onerror); - interval = setInterval(ping, 30000); } function close(callback) { - if (interval !== null) { - clearInterval(interval); - } server.close(); httpserver.close(callback); } diff --git a/lib/server/WebSocketService.js b/lib/server/WebSocketService.js index 0332585..0779cee 100644 --- a/lib/server/WebSocketService.js +++ b/lib/server/WebSocketService.js @@ -13,7 +13,7 @@ * * * Hprose WebSocket Service for Node.js. * * * - * LastModified: Jun 28, 2017 * + * LastModified: Sep 30, 2016 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -105,10 +105,6 @@ function WebSocketService() { ws.close(); return; } - ws.isAlive = true; - ws.on('pong', function() { - ws.isAlive = true; - }); ws.on('close', function() { try { self.emit('close',context); diff --git a/package.json b/package.json index 39eedc2..62734da 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "lib": "lib/" }, "main": "lib/hprose.js", - "optionalDependencies": { "ws": "~3.0.0" }, + "optionalDependencies": { "ws": "~2.3.1" }, "devDependencies": { "promises-aplus-tests": "*" }, From bfc479201747d49b5dd08a2e895a6eb425ff98e9 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 28 Jun 2017 10:35:41 +0800 Subject: [PATCH 111/131] Revert "Update to 2.0.44" This reverts commit f297c9aefd7f00a1467781a05c4d3e0f8d98a429. --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 62734da..29d27ec 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.44", + "version": "2.0.43", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From c94c0ba5abdbb6b1e0c46f845526cd02921b72d9 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Wed, 28 Jun 2017 10:37:31 +0800 Subject: [PATCH 112/131] Update to 2.0.44 --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 29d27ec..39eedc2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.43", + "version": "2.0.44", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ @@ -50,7 +50,7 @@ "lib": "lib/" }, "main": "lib/hprose.js", - "optionalDependencies": { "ws": "~2.3.1" }, + "optionalDependencies": { "ws": "~3.0.0" }, "devDependencies": { "promises-aplus-tests": "*" }, From c25bdf1363d92515a9dba1a68b91e7e671e9962e Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 20 Aug 2017 11:54:46 +0800 Subject: [PATCH 113/131] Fixed connection leak. --- lib/client/WebSocketClient.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/client/WebSocketClient.js b/lib/client/WebSocketClient.js index a39195d..0d8b60d 100644 --- a/lib/client/WebSocketClient.js +++ b/lib/client/WebSocketClient.js @@ -12,7 +12,7 @@ * * * Hprose WebSocket Client for HTML5. * * * - * LastModified: Dec 2, 2016 * + * LastModified: Aug 20, 2017 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -113,9 +113,9 @@ function WebSocketClient(uri, functions, settings) { _futures[id] = future; if (context.timeout > 0) { future = future.timeout(context.timeout).catchError(function(e) { - ws = null; delete _futures[id]; --_count; + close(); throw e; }, function(e) { From fe270210980dfcbaf530d9b71c84f7ba16cf554d Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 20 Aug 2017 11:54:55 +0800 Subject: [PATCH 114/131] Changed default subscribe timeout to 5 minutes. --- lib/client/Client.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index 7460745..30cb46f 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -13,7 +13,7 @@ * * * HproseClient for Node.js. * * * - * LastModified: Nov 19, 2016 * + * LastModified: Aug 20, 2017 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -955,7 +955,8 @@ function Client(uri, functions, settings) { }); return; } - if (timeout === undefined) { timeout = _timeout; } + // Default subscribe timeout is 5 minutes. + if (timeout === undefined) { timeout = 300000; } var topic = getTopic(name, id); if (topic === null) { var cb = function() { From 4ca8b87ea0df654439e1f9a3bb6a60890af0f3b3 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 20 Aug 2017 17:27:14 +0800 Subject: [PATCH 115/131] Fixed #15 --- example/proxyclient.js | 26 +++++++++++++++++++-- lib/client/Client.js | 51 ++++++++++++++++++++++++++++++++++++------ 2 files changed, 68 insertions(+), 9 deletions(-) diff --git a/example/proxyclient.js b/example/proxyclient.js index 5140f69..66770c7 100644 --- a/example/proxyclient.js +++ b/example/proxyclient.js @@ -2,11 +2,33 @@ 'use strict'; var hprose = require('hprose'); -var client = hprose.Client.create('tcp://127.0.0.1:1234/', ['hello']); +var client = hprose.Client.create('tcp://127.0.0.1:1234/', []); client.fullDuplex = true; client.maxPoolSize = 1; -client.hello("World", function(result) { +var proxy = client.useService(); + +proxy.hello("World", function(result) { console.log(result); }, function(name, error) { console.error(error); }); + +var weeks = { + 'Monday': 'Mon', + 'Tuesday': 'Tue', + 'Wednesday': 'Wed', + 'Thursday': 'Thu', + 'Friday': 'Fri', + 'Saturday': 'Sat', + 'Sunday': 'Sun', +}; + +proxy.swapKeyAndValue.onsuccess = function(result, args) { + console.log(weeks.constructor, weeks); + console.log(result.constructor, result); + console.log(args.constructor, args); +}; + +proxy.swapKeyAndValue.byref = true; + +proxy.swapKeyAndValue(weeks); \ No newline at end of file diff --git a/lib/client/Client.js b/lib/client/Client.js index 30cb46f..798f569 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -45,13 +45,45 @@ var s_number = 'number'; var s_function = 'function'; var s_object = 'object'; -function HproseProxy(setFunction, ns) { +function HproseOldProxy(setFunction, ns) { + var settings = {}; + var target = {}; this.get = function(proxy, name) { if (ns) { name = ns + '_' + name; } - return Proxy.createFunction( - new HproseProxy(setFunction, name), - setFunction(this, name) - ); + if (name === 'then') { return undefined; } + if (!proxy.hasOwnProperty(name)) { + settings[name] = {}; + var handler = new HproseOldProxy(setFunction, name); + handler.set = function(proxy, prop, value) { + settings[name][prop] = value; + return true; + }; + target[name] = Proxy.createFunction(handler, setFunction(settings, name)); + } + return target[name]; + }; +} + +function HproseProxy(setFunction, ns) { + var settings = {}; + this.get = function(target, prop, receiver) { + var name = prop.toString(); + if (ns) { name = ns + '_' + name; } + if (name === 'then') { return undefined; } + if (!target.hasOwnProperty(name)) { + settings[name] = {}; + var handler = new HproseProxy(setFunction, name); + var func = setFunction(settings, name); + handler.apply = function(target, thisArg, argumentsList) { + return func.apply(null, argumentsList); + } + handler.set = function(target, prop, value, receiver) { + settings[name][prop] = value; + return true; + }; + target[name] = new Proxy(function() {}, handler); + } + return target[name]; }; } @@ -874,11 +906,16 @@ function Client(uri, functions, settings) { setFunctions(stub, functions); } else { - if (typeof(Proxy) === 'undefined' || !('create' in Proxy)) { + if (typeof(Proxy) === 'undefined') { process.nextTick(initService, stub); return _ready; } - stub = Proxy.create(new HproseProxy(setFunction)); + if ('create' in Proxy) { + stub = Proxy.create(new HproseOldProxy(setFunction)); + } + else { + stub = new Proxy({}, new HproseProxy(setFunction)); + } } _ready.resolve(stub); return stub; From 6f75a14da1e245bbdd9a6ba871a0ead6fd801a9c Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 20 Aug 2017 17:27:26 +0800 Subject: [PATCH 116/131] Update to 2.0.45 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 39eedc2..265e4b4 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.44", + "version": "2.0.45", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From a881275b2dd7d18b2cdc199f1b73a5285b87546a Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Sun, 20 Aug 2017 17:34:50 +0800 Subject: [PATCH 117/131] Update ws to 3.1.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 265e4b4..22a84a5 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "lib": "lib/" }, "main": "lib/hprose.js", - "optionalDependencies": { "ws": "~3.0.0" }, + "optionalDependencies": { "ws": ">=3.1.0" }, "devDependencies": { "promises-aplus-tests": "*" }, From e922b707461954350e9c73f666d42a0e0ffdf70a Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Tue, 6 Feb 2018 16:05:33 +0800 Subject: [PATCH 118/131] Happy new year! --- LICENSE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE.md b/LICENSE.md index 02bb1a1..70a0e7b 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2008-2016 http://hprose.com +Copyright (c) 2008-2018 http://hprose.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in From 7850cdf3ae7b6cb08957f298c0f1efa338e6ec2b Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Tue, 6 Feb 2018 16:06:32 +0800 Subject: [PATCH 119/131] Added namespace support for auto fetching the methods. --- lib/client/Client.js | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/lib/client/Client.js b/lib/client/Client.js index 798f569..0a89255 100644 --- a/lib/client/Client.js +++ b/lib/client/Client.js @@ -6,14 +6,13 @@ | http://www.hprose.org/ | | | \**********************************************************/ - /**********************************************************\ * * * hprose/client/Client.js * * * * HproseClient for Node.js. * * * - * LastModified: Aug 20, 2017 * + * LastModified: Feb 6, 2018 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -205,6 +204,27 @@ function Client(uri, functions, settings) { return null; } + function normalizeFunctions(functions) { + var root = [Object.create(null)]; + for (var i in functions) { + var func = functions[i].split('_'); + var n = func.length - 1; + if (n > 0) { + var node = root; + for (var j = 0; j < n; j++) { + var f = func[j]; + if (node[0][f] === undefined) { + node[0][f] = [Object.create(null)]; + } + node = node[0][f]; + } + node.push(func[n]); + } + root.push(functions[i]); + } + return root; + } + function initService(stub) { var context = { retry: _retry, @@ -226,7 +246,7 @@ function Client(uri, functions, settings) { error = new Error(reader.readString()); break; case Tags.TagFunctions: - var functions = reader.readList(); + var functions = normalizeFunctions(reader.readList()); reader.checkTag(Tags.TagEnd); setFunctions(stub, functions); break; From d422c53617660378bc5c07eff939e54b082e28c0 Mon Sep 17 00:00:00 2001 From: Ma Bingyao Date: Tue, 6 Feb 2018 16:06:50 +0800 Subject: [PATCH 120/131] Update to 2.0.46 --- package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 22a84a5..0c107af 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.45", + "version": "2.0.46", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ @@ -50,7 +50,7 @@ "lib": "lib/" }, "main": "lib/hprose.js", - "optionalDependencies": { "ws": ">=3.1.0" }, + "optionalDependencies": { "ws": ">=4.0.0" }, "devDependencies": { "promises-aplus-tests": "*" }, From 58cb2323bd57f5c9a503afea642237762bcf772b Mon Sep 17 00:00:00 2001 From: andot Date: Fri, 23 Mar 2018 19:43:18 +0800 Subject: [PATCH 121/131] Fixed #19 --- lib/server/HttpService.js | 5 +++++ package.json | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/server/HttpService.js b/lib/server/HttpService.js index 5ccff92..8afdd7a 100644 --- a/lib/server/HttpService.js +++ b/lib/server/HttpService.js @@ -99,6 +99,7 @@ function HttpService() { function sendHeader(context) { var resp = context.response; + resp.statusCode = 200; resp.setHeader('Content-Type', 'text/plain'); if (_P3P) { resp.setHeader('P3P', @@ -225,6 +226,7 @@ function HttpService() { }; request.socket.setTimeout(self.timeout); var bytes = new BytesIO(); + var done = new Future(); request.on('data', function(data) { bytes.write(data); }); request.on('end', function() { if (_clientAccessPolicyXmlContent !== null && clientAccessPolicyXmlHandler(request, response)) { return; } @@ -234,6 +236,7 @@ function HttpService() { } catch (e) { send(self.endError(e, context), response); + done.resolve(true); return; } var result = ''; @@ -244,7 +247,9 @@ function HttpService() { result = self.defaultHandle(bytes.bytes, context); } send(result, response); + done.resolve(true); }); + return done; } Object.defineProperties(this, { diff --git a/package.json b/package.json index 0c107af..b3abc64 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.46", + "version": "2.0.47", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From ab7e98687cac15d5bc8f527f6c10cf81ec253786 Mon Sep 17 00:00:00 2001 From: andot Date: Fri, 23 Mar 2018 19:49:27 +0800 Subject: [PATCH 122/131] Update the LastModified Date --- lib/server/HttpService.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/server/HttpService.js b/lib/server/HttpService.js index 8afdd7a..71d078d 100644 --- a/lib/server/HttpService.js +++ b/lib/server/HttpService.js @@ -13,7 +13,7 @@ * * * Hprose Http Service for Node.js. * * * - * LastModified: Mar 3, 2016 * + * LastModified: Mar 23, 2018 * * Author: Ma Bingyao * * * \**********************************************************/ From 62666f7dff72f2da97f24085e81fb206dcd4010a Mon Sep 17 00:00:00 2001 From: andot Date: Thu, 29 Mar 2018 13:13:13 +0800 Subject: [PATCH 123/131] Fixed async function name --- example/client.js | 5 +++++ example/server.js | 4 ++-- lib/server/Service.js | 4 ++-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/example/client.js b/example/client.js index 345bcea..c5cafe8 100644 --- a/example/client.js +++ b/example/client.js @@ -27,6 +27,11 @@ for (var i = 0; i < max; i++) { } var end = new Date().getTime(); console.log(end - start); + +(async function() { + console.log(await proxy.hello2("async world")); +})(); + client.batch.begin(); proxy.getMaps('name', 'age', 'age', function(result) { console.log(result); diff --git a/example/server.js b/example/server.js index f34ff0d..177badb 100644 --- a/example/server.js +++ b/example/server.js @@ -9,8 +9,8 @@ function hello(name, context) { return 'Hello ' + name + '! -- ' + context.socket.remoteAddress; } -function hello2(name) { - return 'Hello ' + name + '!'; +async function hello2(name) { + return await 'Hello ' + name + '!'; } function asyncHello(name, callback) { diff --git a/lib/server/Service.js b/lib/server/Service.js index 3e75633..5ca6d6f 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Dec 5, 2016 * + * LastModified: Mar 29, 2018 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -51,7 +51,7 @@ function callService(args, context) { function getFuncName(func, obj) { var f = func.toString(); - var funcname = f.substr(0, f.indexOf('(')).replace(/(^\s*function\*?\s*)|(\s*$)/ig, ''); + var funcname = f.substr(0, f.indexOf('(')).replace(/(^\s*(async)?\s*function\*?\s*)|(\s*$)/ig, ''); if ((funcname === '') && obj) { for (var name in obj) { if (obj[name] === func) { return name; } From 69e0a7f763c44b2e065278776b5dfde96f5d439f Mon Sep 17 00:00:00 2001 From: andot Date: Thu, 29 Mar 2018 13:13:41 +0800 Subject: [PATCH 124/131] Update to v2.0.48 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index b3abc64..ec9adc1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.47", + "version": "2.0.48", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From d4900e8ec67d2f3453e39621a986c6354d2ce4f6 Mon Sep 17 00:00:00 2001 From: andot Date: Thu, 12 Apr 2018 23:28:48 +0800 Subject: [PATCH 125/131] Fixed remove --- lib/server/Service.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/server/Service.js b/lib/server/Service.js index 5ca6d6f..16406c7 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -13,7 +13,7 @@ * * * Hprose Service for Node.js. * * * - * LastModified: Mar 29, 2018 * + * LastModified: Apr 12, 2018 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -519,9 +519,9 @@ function Service() { function remove(alias) { var name = alias.toLowerCase(); if (_calls[name]) { - var index = _name.indexOf(alias); + var index = _names.indexOf(alias); if (index >= 0) { - _name.splice(index, 1); + _names.splice(index, 1); } delete _calls[name]; } From a91730186a363e1b6dcb6d89e42c3f6ae418cbac Mon Sep 17 00:00:00 2001 From: WangPengJu <19352226@qq.com> Date: Fri, 13 Apr 2018 00:05:02 +0800 Subject: [PATCH 126/131] Create index.d.ts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 类型定义文件 --- index.d.ts | 297 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 297 insertions(+) create mode 100644 index.d.ts diff --git a/index.d.ts b/index.d.ts new file mode 100644 index 0000000..2fd783f --- /dev/null +++ b/index.d.ts @@ -0,0 +1,297 @@ +declare namespace hprose { + class TimeoutError extends Error { + constructor(message?: any); + } +} +declare namespace hprose { + function generic(method: any): (context: any) => any; + function toArray(arrayLikeObject: any): any[]; + function toBinaryString(bytes: any): any; + function toUint8Array(bs: any): Uint8Array; + function isObjectEmpty(obj: any): boolean; +} +declare function genericMethods(obj: any, properties: any): void; +declare namespace hprose { + function Future(computation?: any): void; + let rejected: (e: any) => any; + let resolved: (v: any) => any; + function thunkify(fn: any): () => (done: any) => void; + function promisify(fn: any): () => any; + function co(gen: any): any; + function Completer(): void; + let deferred: () => any; +} +declare namespace hprose { + function isError(err: any): boolean; +} +declare namespace hprose { + let ResultMode: { + Normal: number; + Serialized: number; + Raw: number; + RawWithEndTag: number; + }; + let Normal: number; + let Serialized: number; + let Raw: number; + let RawWithEndTag: number; +} +declare namespace hprose { + function BytesIO(arg?: any): void; +} +declare namespace hprose { + function register(cls: any, alias: any): void; + let ClassManager: any; +} +declare namespace hprose { + let Tags: { + TagInteger: number; + TagLong: number; + TagDouble: number; + TagNull: number; + TagEmpty: number; + TagTrue: number; + TagFalse: number; + TagNaN: number; + TagInfinity: number; + TagDate: number; + TagTime: number; + TagUTC: number; + TagBytes: number; + TagUTF8Char: number; + TagString: number; + TagGuid: number; + TagList: number; + TagMap: number; + TagClass: number; + TagObject: number; + TagRef: number; + TagPos: number; + TagNeg: number; + TagSemicolon: number; + TagOpenbrace: number; + TagClosebrace: number; + TagQuote: number; + TagPoint: number; + TagFunctions: number; + TagCall: number; + TagResult: number; + TagArgument: number; + TagError: number; + TagEnd: number; + }; +} +declare namespace hprose { + function Writer(stream: any, simple: any): void; +} +declare namespace hprose { + function RawReader(stream: any): void; + function Reader(stream: any, simple?: any, useHarmonyMap?: any): void; +} +declare namespace hprose { + function serialize(value: any, simple: any): any; + function unserialize(stream: any, simple: any, useHarmonyMap: any): any; + let Formatter: { + serialize: (value: any, simple: any) => any; + unserialize: typeof unserialize; + }; +} +declare namespace hprose { + function Client(uri: any, functions: any, settings: any): void; +} +declare namespace hprose { + function HttpClient(uri: any, functions: any, settings: any): any; +} +declare namespace hprose { + function SocketClient(uri: any, functions: any, settings: any): any; + let TcpClient: typeof SocketClient; + let UnixClient: typeof SocketClient; +} +declare namespace hprose { + function WebSocketClient(uri: any, functions: any, settings: any): any; +} +declare namespace hprose { + function Service(): void; +} +declare namespace hprose { + function HttpService(): void; +} +declare namespace hprose { + function HttpServer(port: any, hostname: any, tlsOptions: any): void; +} +declare namespace hprose { + function SocketService(): void; +} +declare namespace hprose { + function SocketServer(options: any, tlsOptions: any): void; + let TcpServer: typeof SocketServer; + let UnixServer: typeof SocketServer; +} +declare namespace hprose { + function WebSocketService(): void; +} +declare namespace hprose { + function WebSocketServer(options: any, tlsOptions: any, handler: any): void; +} +declare namespace hprose { + function Server(uri: any, tlsOptions: any, handler: any): any; +} +declare namespace hprose { + function JSONRPCClientFilter(version: any): void; +} +declare namespace hprose { + function JSONRPCServiceFilter(): void; +} +declare let HproseCompleter: typeof hprose.Completer; +declare let HproseFuture: typeof hprose.Future; +declare let HproseResultMode: { + Normal: number; + Serialized: number; + Raw: number; + RawWithEndTag: number; +}; +declare let HproseBytesIO: typeof hprose.BytesIO; +declare let HproseClassManager: any; +declare let HproseTags: { + TagInteger: number; + TagLong: number; + TagDouble: number; + TagNull: number; + TagEmpty: number; + TagTrue: number; + TagFalse: number; + TagNaN: number; + TagInfinity: number; + TagDate: number; + TagTime: number; + TagUTC: number; + TagBytes: number; + TagUTF8Char: number; + TagString: number; + TagGuid: number; + TagList: number; + TagMap: number; + TagClass: number; + TagObject: number; + TagRef: number; + TagPos: number; + TagNeg: number; + TagSemicolon: number; + TagOpenbrace: number; + TagClosebrace: number; + TagQuote: number; + TagPoint: number; + TagFunctions: number; + TagCall: number; + TagResult: number; + TagArgument: number; + TagError: number; + TagEnd: number; +}; +declare let HproseWriter: typeof hprose.Writer; +declare let HproseRawReader: typeof hprose.RawReader; +declare let HproseFormatter: { + serialize: (value: any, simple: any) => any; + unserialize: typeof hprose.unserialize; +}; +declare let HproseClient: typeof hprose.Client; +declare let HproseHttpClient: typeof hprose.HttpClient; +declare let HproseSocketClient: typeof hprose.SocketClient; +declare let HproseTcpClient: typeof hprose.SocketClient; +declare let HproseUnixClient: typeof hprose.SocketClient; +declare let HproseWebSocketClient: typeof hprose.WebSocketClient; +declare let HproseService: typeof hprose.Service; +declare let HproseServer: typeof hprose.Server; +declare let HproseHttpService: typeof hprose.HttpService; +declare let HproseHttpServer: typeof hprose.HttpServer; +declare let HproseSocketService: typeof hprose.SocketService; +declare let HproseSocketServer: typeof hprose.SocketServer; +declare let HproseTcpServer: typeof hprose.SocketServer; +declare let HproseUnixServer: typeof hprose.SocketServer; +declare let HproseWebSocketService: typeof hprose.WebSocketService; +declare let HproseWebSocketServer: typeof hprose.WebSocketServer; +declare let HproseJSONRPCClientFilter: typeof hprose.JSONRPCClientFilter; +declare let HproseJSONRPCServiceFilter: typeof hprose.JSONRPCServiceFilter; +declare namespace hprose { + let common: { + Completer: typeof Completer; + Future: typeof Future; + ResultMode: { + Normal: number; + Serialized: number; + Raw: number; + RawWithEndTag: number; + }; + }; + let io: { + BytesIO: typeof BytesIO; + ClassManager: any; + Tags: { + TagInteger: number; + TagLong: number; + TagDouble: number; + TagNull: number; + TagEmpty: number; + TagTrue: number; + TagFalse: number; + TagNaN: number; + TagInfinity: number; + TagDate: number; + TagTime: number; + TagUTC: number; + TagBytes: number; + TagUTF8Char: number; + TagString: number; + TagGuid: number; + TagList: number; + TagMap: number; + TagClass: number; + TagObject: number; + TagRef: number; + TagPos: number; + TagNeg: number; + TagSemicolon: number; + TagOpenbrace: number; + TagClosebrace: number; + TagQuote: number; + TagPoint: number; + TagFunctions: number; + TagCall: number; + TagResult: number; + TagArgument: number; + TagError: number; + TagEnd: number; + }; + RawReader: typeof RawReader; + Reader: typeof Reader; + Writer: typeof Writer; + Formatter: { + serialize: (value: any, simple: any) => any; + unserialize: typeof unserialize; + }; + }; + let client: { + Client: typeof Client; + HttpClient: typeof HttpClient; + SocketClient: typeof SocketClient; + TcpClient: typeof SocketClient; + UnixClient: typeof SocketClient; + WebSocketClient: typeof WebSocketClient; + }; + let server: { + Service: typeof Service; + Server: typeof Server; + HttpService: typeof HttpService; + HttpServer: typeof HttpServer; + SocketService: typeof SocketService; + SocketServer: typeof SocketServer; + TcpServer: typeof SocketServer; + UnixServer: typeof SocketServer; + WebSocketService: typeof WebSocketService; + WebSocketServer: typeof WebSocketServer; + }; + let filter: { + JSONRPCClientFilter: typeof JSONRPCClientFilter; + JSONRPCServiceFilter: typeof JSONRPCServiceFilter; + }; +} From b0aeebd3d3ff03fdf2e4af2de8d29b0043e7ad39 Mon Sep 17 00:00:00 2001 From: andot Date: Fri, 13 Apr 2018 00:24:17 +0800 Subject: [PATCH 127/131] Update to v2.0.49 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ec9adc1..9b60ffc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.48", + "version": "2.0.49", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 0893d39323605c31bfde94cdb6eefebeb85aa9fb Mon Sep 17 00:00:00 2001 From: andot Date: Wed, 6 Jun 2018 18:10:37 +0800 Subject: [PATCH 128/131] Fixed async function in koa. --- lib/server/HttpService.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/server/HttpService.js b/lib/server/HttpService.js index 71d078d..54920e4 100644 --- a/lib/server/HttpService.js +++ b/lib/server/HttpService.js @@ -13,7 +13,7 @@ * * * Hprose Http Service for Node.js. * * * - * LastModified: Mar 23, 2018 * + * LastModified: Jun 6, 2018 * * Author: Ma Bingyao * * * \**********************************************************/ @@ -247,7 +247,7 @@ function HttpService() { result = self.defaultHandle(bytes.bytes, context); } send(result, response); - done.resolve(true); + done.resolve(result); }); return done; } From 4602ef542a55bee918d9209eb85dff4539f2a93f Mon Sep 17 00:00:00 2001 From: andot Date: Wed, 6 Jun 2018 18:11:23 +0800 Subject: [PATCH 129/131] Update to 2.0.50 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 9b60ffc..1d265c7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.49", + "version": "2.0.50", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From f7c301a92f44264e648346e23e62ee8e3b18e66a Mon Sep 17 00:00:00 2001 From: andot Date: Thu, 14 Jun 2018 13:15:04 +0800 Subject: [PATCH 130/131] Removed index.d.ts --- index.d.ts | 297 --------------------------------------------------- package.json | 2 +- 2 files changed, 1 insertion(+), 298 deletions(-) delete mode 100644 index.d.ts diff --git a/index.d.ts b/index.d.ts deleted file mode 100644 index 2fd783f..0000000 --- a/index.d.ts +++ /dev/null @@ -1,297 +0,0 @@ -declare namespace hprose { - class TimeoutError extends Error { - constructor(message?: any); - } -} -declare namespace hprose { - function generic(method: any): (context: any) => any; - function toArray(arrayLikeObject: any): any[]; - function toBinaryString(bytes: any): any; - function toUint8Array(bs: any): Uint8Array; - function isObjectEmpty(obj: any): boolean; -} -declare function genericMethods(obj: any, properties: any): void; -declare namespace hprose { - function Future(computation?: any): void; - let rejected: (e: any) => any; - let resolved: (v: any) => any; - function thunkify(fn: any): () => (done: any) => void; - function promisify(fn: any): () => any; - function co(gen: any): any; - function Completer(): void; - let deferred: () => any; -} -declare namespace hprose { - function isError(err: any): boolean; -} -declare namespace hprose { - let ResultMode: { - Normal: number; - Serialized: number; - Raw: number; - RawWithEndTag: number; - }; - let Normal: number; - let Serialized: number; - let Raw: number; - let RawWithEndTag: number; -} -declare namespace hprose { - function BytesIO(arg?: any): void; -} -declare namespace hprose { - function register(cls: any, alias: any): void; - let ClassManager: any; -} -declare namespace hprose { - let Tags: { - TagInteger: number; - TagLong: number; - TagDouble: number; - TagNull: number; - TagEmpty: number; - TagTrue: number; - TagFalse: number; - TagNaN: number; - TagInfinity: number; - TagDate: number; - TagTime: number; - TagUTC: number; - TagBytes: number; - TagUTF8Char: number; - TagString: number; - TagGuid: number; - TagList: number; - TagMap: number; - TagClass: number; - TagObject: number; - TagRef: number; - TagPos: number; - TagNeg: number; - TagSemicolon: number; - TagOpenbrace: number; - TagClosebrace: number; - TagQuote: number; - TagPoint: number; - TagFunctions: number; - TagCall: number; - TagResult: number; - TagArgument: number; - TagError: number; - TagEnd: number; - }; -} -declare namespace hprose { - function Writer(stream: any, simple: any): void; -} -declare namespace hprose { - function RawReader(stream: any): void; - function Reader(stream: any, simple?: any, useHarmonyMap?: any): void; -} -declare namespace hprose { - function serialize(value: any, simple: any): any; - function unserialize(stream: any, simple: any, useHarmonyMap: any): any; - let Formatter: { - serialize: (value: any, simple: any) => any; - unserialize: typeof unserialize; - }; -} -declare namespace hprose { - function Client(uri: any, functions: any, settings: any): void; -} -declare namespace hprose { - function HttpClient(uri: any, functions: any, settings: any): any; -} -declare namespace hprose { - function SocketClient(uri: any, functions: any, settings: any): any; - let TcpClient: typeof SocketClient; - let UnixClient: typeof SocketClient; -} -declare namespace hprose { - function WebSocketClient(uri: any, functions: any, settings: any): any; -} -declare namespace hprose { - function Service(): void; -} -declare namespace hprose { - function HttpService(): void; -} -declare namespace hprose { - function HttpServer(port: any, hostname: any, tlsOptions: any): void; -} -declare namespace hprose { - function SocketService(): void; -} -declare namespace hprose { - function SocketServer(options: any, tlsOptions: any): void; - let TcpServer: typeof SocketServer; - let UnixServer: typeof SocketServer; -} -declare namespace hprose { - function WebSocketService(): void; -} -declare namespace hprose { - function WebSocketServer(options: any, tlsOptions: any, handler: any): void; -} -declare namespace hprose { - function Server(uri: any, tlsOptions: any, handler: any): any; -} -declare namespace hprose { - function JSONRPCClientFilter(version: any): void; -} -declare namespace hprose { - function JSONRPCServiceFilter(): void; -} -declare let HproseCompleter: typeof hprose.Completer; -declare let HproseFuture: typeof hprose.Future; -declare let HproseResultMode: { - Normal: number; - Serialized: number; - Raw: number; - RawWithEndTag: number; -}; -declare let HproseBytesIO: typeof hprose.BytesIO; -declare let HproseClassManager: any; -declare let HproseTags: { - TagInteger: number; - TagLong: number; - TagDouble: number; - TagNull: number; - TagEmpty: number; - TagTrue: number; - TagFalse: number; - TagNaN: number; - TagInfinity: number; - TagDate: number; - TagTime: number; - TagUTC: number; - TagBytes: number; - TagUTF8Char: number; - TagString: number; - TagGuid: number; - TagList: number; - TagMap: number; - TagClass: number; - TagObject: number; - TagRef: number; - TagPos: number; - TagNeg: number; - TagSemicolon: number; - TagOpenbrace: number; - TagClosebrace: number; - TagQuote: number; - TagPoint: number; - TagFunctions: number; - TagCall: number; - TagResult: number; - TagArgument: number; - TagError: number; - TagEnd: number; -}; -declare let HproseWriter: typeof hprose.Writer; -declare let HproseRawReader: typeof hprose.RawReader; -declare let HproseFormatter: { - serialize: (value: any, simple: any) => any; - unserialize: typeof hprose.unserialize; -}; -declare let HproseClient: typeof hprose.Client; -declare let HproseHttpClient: typeof hprose.HttpClient; -declare let HproseSocketClient: typeof hprose.SocketClient; -declare let HproseTcpClient: typeof hprose.SocketClient; -declare let HproseUnixClient: typeof hprose.SocketClient; -declare let HproseWebSocketClient: typeof hprose.WebSocketClient; -declare let HproseService: typeof hprose.Service; -declare let HproseServer: typeof hprose.Server; -declare let HproseHttpService: typeof hprose.HttpService; -declare let HproseHttpServer: typeof hprose.HttpServer; -declare let HproseSocketService: typeof hprose.SocketService; -declare let HproseSocketServer: typeof hprose.SocketServer; -declare let HproseTcpServer: typeof hprose.SocketServer; -declare let HproseUnixServer: typeof hprose.SocketServer; -declare let HproseWebSocketService: typeof hprose.WebSocketService; -declare let HproseWebSocketServer: typeof hprose.WebSocketServer; -declare let HproseJSONRPCClientFilter: typeof hprose.JSONRPCClientFilter; -declare let HproseJSONRPCServiceFilter: typeof hprose.JSONRPCServiceFilter; -declare namespace hprose { - let common: { - Completer: typeof Completer; - Future: typeof Future; - ResultMode: { - Normal: number; - Serialized: number; - Raw: number; - RawWithEndTag: number; - }; - }; - let io: { - BytesIO: typeof BytesIO; - ClassManager: any; - Tags: { - TagInteger: number; - TagLong: number; - TagDouble: number; - TagNull: number; - TagEmpty: number; - TagTrue: number; - TagFalse: number; - TagNaN: number; - TagInfinity: number; - TagDate: number; - TagTime: number; - TagUTC: number; - TagBytes: number; - TagUTF8Char: number; - TagString: number; - TagGuid: number; - TagList: number; - TagMap: number; - TagClass: number; - TagObject: number; - TagRef: number; - TagPos: number; - TagNeg: number; - TagSemicolon: number; - TagOpenbrace: number; - TagClosebrace: number; - TagQuote: number; - TagPoint: number; - TagFunctions: number; - TagCall: number; - TagResult: number; - TagArgument: number; - TagError: number; - TagEnd: number; - }; - RawReader: typeof RawReader; - Reader: typeof Reader; - Writer: typeof Writer; - Formatter: { - serialize: (value: any, simple: any) => any; - unserialize: typeof unserialize; - }; - }; - let client: { - Client: typeof Client; - HttpClient: typeof HttpClient; - SocketClient: typeof SocketClient; - TcpClient: typeof SocketClient; - UnixClient: typeof SocketClient; - WebSocketClient: typeof WebSocketClient; - }; - let server: { - Service: typeof Service; - Server: typeof Server; - HttpService: typeof HttpService; - HttpServer: typeof HttpServer; - SocketService: typeof SocketService; - SocketServer: typeof SocketServer; - TcpServer: typeof SocketServer; - UnixServer: typeof SocketServer; - WebSocketService: typeof WebSocketService; - WebSocketServer: typeof WebSocketServer; - }; - let filter: { - JSONRPCClientFilter: typeof JSONRPCClientFilter; - JSONRPCServiceFilter: typeof JSONRPCServiceFilter; - }; -} diff --git a/package.json b/package.json index 1d265c7..0266944 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hprose", - "version": "2.0.50", + "version": "2.0.51", "homepage": "https://github.com/hprose/hprose-nodejs", "description": "hprose for node.js", "keywords": [ From 323e8f141c92f4e848c5cee325266d6867e46148 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BC=BA?= Date: Fri, 19 Apr 2019 15:17:28 +0800 Subject: [PATCH 131/131] add function getNames --- lib/server/Service.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/server/Service.js b/lib/server/Service.js index 16406c7..35337a0 100644 --- a/lib/server/Service.js +++ b/lib/server/Service.js @@ -1139,6 +1139,10 @@ function Service() { addInvokeHandler(handler); return self; } + function getNames() { + return _names; + } + var beforeFilter = Object.create(null, { use: { value: function(handler) { addBeforeFilterHandler(handler); @@ -1193,6 +1197,7 @@ function Service() { idlist: { value: idlist }, exist: { value: exist }, use: { value: use }, + getNames: { value: getNames }, beforeFilter: { value: beforeFilter }, afterFilter: { value: afterFilter } });