Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

turn tabs to spaces for core

Change-Id: I613d2f4f4ffc4129a83b7ef3069607c350398734
  • Loading branch information...
commit 92663ae7e646cada1ef4ac27c854560c37d37cbd 1 parent b6ed7da
changchang changchang authored
Showing with 2,346 additions and 2,337 deletions.
  1. +20 −0 .jshintrc
  2. +260 −260 lib/application.js
  3. +18 −18 lib/common/remote/backend/msgRemote.js
  4. +28 −28 lib/common/remote/frontend/channelRemote.js
  5. +5 −5 lib/common/remote/frontend/sessionRemote.js
  6. +280 −281 lib/common/service/channelService.js
  7. +22 −22 lib/common/service/connectionService.js
  8. +45 −46 lib/common/service/filterService.js
  9. +29 −29 lib/common/service/handlerService.js
  10. +44 −44 lib/common/service/localSessionService.js
  11. +423 −423 lib/common/service/sessionService.js
  12. +39 −45 lib/common/service/taskManager.js
  13. +4 −4 lib/components/channel.js
  14. +17 −17 lib/components/connection.js
  15. +114 −114 lib/components/connector.js
  16. +3 −3 lib/components/localSession.js
  17. +6 −6 lib/components/master.js
  18. +4 −4 lib/components/monitor.js
  19. +99 −99 lib/components/proxy.js
  20. +45 −45 lib/components/remote.js
  21. +15 −15 lib/components/server.js
  22. +35 −35 lib/components/session.js
  23. +41 −41 lib/components/sync.js
  24. +10 −10 lib/connectors/sioconnector.js
  25. +30 −30 lib/connectors/siosocket.js
  26. +14 −15 lib/filters/handler/serial.js
  27. +15 −15 lib/filters/handler/time.js
  28. +17 −17 lib/filters/handler/timeout.js
  29. +16 −18 lib/filters/rpc/rpcLog.js
  30. +72 −72 lib/master/master.js
  31. +166 −166 lib/master/starter.js
  32. +13 −13 lib/modules/afterStart.js
  33. +69 −69 lib/modules/console.js
  34. +45 −45 lib/monitor/monitor.js
  35. +27 −27 lib/pomelo.js
  36. +144 −144 lib/server/server.js
  37. +41 −41 lib/util/countDownLatch.js
  38. +3 −3 lib/util/log.js
  39. +9 −9 lib/util/pathUtil.js
  40. +54 −54 lib/util/utils.js
  41. +4 −4 scripts/getSenceUser.js
  42. +1 −1  scripts/getSystemInfo.js
20 .jshintrc
View
@@ -0,0 +1,20 @@
+{
+ "predef": [
+ "describe",
+ "it",
+ "before",
+ "after",
+ "window",
+ "__resources__"
+ ],
+ "es5": true,
+ "node": true,
+ "eqeqeq": true,
+ "undef": true,
+ "curly": true,
+ "bitwise": true,
+ "immed": false,
+ "newcap": true,
+ "nonew": true,
+ "white": false
+}
520 lib/application.js
View
@@ -24,8 +24,8 @@ var Application = module.exports = {};
* Application states
*/
var STATE_INITED = 1; // app has inited
-var STATE_START = 2; // app start
-var STATE_STARTED = 3; // app has started
+var STATE_START = 2; // app start
+var STATE_STARTED = 3; // app has started
var STATE_STOPED = 4; // app has stoped
/**
@@ -36,30 +36,30 @@ var STATE_STOPED = 4; // app has stoped
* @api private
*/
Application.init = function(opts) {
- opts = opts || {};
- logger.info('app.init invoked');
- this.loaded = [];
- this.components = {};
- this.settings = {};
- this.set('base', opts.base);
- this.defaultConfiguration();
- this.state = STATE_INITED;
- logger.info('application inited: %j', this.get('serverId'));
+ opts = opts || {};
+ logger.info('app.init invoked');
+ this.loaded = [];
+ this.components = {};
+ this.settings = {};
+ this.set('base', opts.base);
+ this.defaultConfiguration();
+ this.state = STATE_INITED;
+ logger.info('application inited: %j', this.get('serverId'));
};
/**
* Get application base path
*
- * // cwd: /home/game/
- * pomelo start
- * // app.getBase() -> /home/game
+ * // cwd: /home/game/
+ * pomelo start
+ * // app.getBase() -> /home/game
*
* @return {String} application base path
*
* @memberOf Application
*/
Application.getBase = function() {
- return this.get('base') || process.cwd();
+ return this.get('base') || process.cwd();
};
/**
@@ -68,12 +68,12 @@ Application.getBase = function() {
* @api private
*/
Application.defaultConfiguration = function () {
- var args = utils.argsInfo(process.argv);
- this.setupEnv(args);
- this.loadServers();
- this.loadConfig('master', this.getBase() + '/config/master.json');
- this.processArgs(args);
- this.configLogger();
+ var args = utils.argsInfo(process.argv);
+ this.setupEnv(args);
+ this.loadServers();
+ this.loadConfig('master', this.getBase() + '/config/master.json');
+ this.processArgs(args);
+ this.configLogger();
};
/**
@@ -81,7 +81,7 @@ Application.defaultConfiguration = function () {
* @api private
*/
Application.setupEnv = function(args) {
- this.set('env', args.env || process.env.NODE_ENV || 'development', true);
+ this.set('env', args.env || process.env.NODE_ENV || 'development', true);
};
/**
@@ -90,19 +90,19 @@ Application.setupEnv = function(args) {
* @api private
*/
Application.loadServers = function() {
- this.loadConfig('servers', this.getBase() + '/config/servers.json');
- var servers = this.get('servers');
- var serverMap = {}, slist, i, l, server;
- for(var serverType in servers) {
- slist = servers[serverType];
- for(i=0, l=slist.length; i<l; i++) {
- server = slist[i];
- server.serverType = serverType;
- serverMap[server.id] = server;
- }
- }
+ this.loadConfig('servers', this.getBase() + '/config/servers.json');
+ var servers = this.get('servers');
+ var serverMap = {}, slist, i, l, server;
+ for(var serverType in servers) {
+ slist = servers[serverType];
+ for(i=0, l=slist.length; i<l; i++) {
+ server = slist[i];
+ server.serverType = serverType;
+ serverMap[server.id] = server;
+ }
+ }
- this.set('__serverMap__', serverMap);
+ this.set('__serverMap__', serverMap);
};
/**
@@ -113,16 +113,16 @@ Application.loadServers = function() {
* @api private
*/
Application.processArgs = function(args){
- var serverType = args.serverType || 'master';
- var serverId = args.serverId || this.get('master').id;
- this.set('main', args.main, true);
- this.set('serverType', serverType, true);
- this.set('serverId', serverId, true);
- if(serverType !== 'master') {
- this.set('curServer', this.getServerById(serverId), true);
- } else {
- this.set('curServer', this.get('master'), true);
- }
+ var serverType = args.serverType || 'master';
+ var serverId = args.serverId || this.get('master').id;
+ this.set('main', args.main, true);
+ this.set('serverType', serverType, true);
+ this.set('serverId', serverId, true);
+ if(serverType !== 'master') {
+ this.set('curServer', this.getServerById(serverId), true);
+ } else {
+ this.set('curServer', this.get('master'), true);
+ }
};
/**
@@ -131,32 +131,32 @@ Application.processArgs = function(args){
* @api private
*/
Application.loadDefaultComponents = function(){
- var pomelo = require('./pomelo');
- // load system default components
- if (this.serverType === 'master') {
- this.load(pomelo.master, this.get('masterConfig'));
- } else {
- this.load(pomelo.proxy, this.get('proxyConfig'));
- if(this.getServerById(this.get('serverId')).port) {
- this.load(pomelo.remote, this.get('remoteConfig'));
- }
- if(this.isFrontend()) {
- this.load(pomelo.connection, this.get('connectionConfig'));
- this.load(pomelo.connector, this.get('connectorConfig'));
- this.load(pomelo.session, this.get('sessionConfig'));
- } else {
- this.load(pomelo.localSession, this.get('localSessionConfig'));
- }
- this.load(pomelo.channel, this.get('channelConfig'));
- this.load(pomelo.server, this.get('serverConfig'));
- }
- this.load(pomelo.monitor, this);
+ var pomelo = require('./pomelo');
+ // load system default components
+ if (this.serverType === 'master') {
+ this.load(pomelo.master, this.get('masterConfig'));
+ } else {
+ this.load(pomelo.proxy, this.get('proxyConfig'));
+ if(this.getServerById(this.get('serverId')).port) {
+ this.load(pomelo.remote, this.get('remoteConfig'));
+ }
+ if(this.isFrontend()) {
+ this.load(pomelo.connection, this.get('connectionConfig'));
+ this.load(pomelo.connector, this.get('connectorConfig'));
+ this.load(pomelo.session, this.get('sessionConfig'));
+ } else {
+ this.load(pomelo.localSession, this.get('localSessionConfig'));
+ }
+ this.load(pomelo.channel, this.get('channelConfig'));
+ this.load(pomelo.server, this.get('serverConfig'));
+ }
+ this.load(pomelo.monitor, this);
};
Application.configLogger = function() {
- if(process.env.POMELO_LOGGER !== 'off') {
- log.configure(this, this.getBase() + '/config/log4js.json');
- }
+ if(process.env.POMELO_LOGGER !== 'off') {
+ log.configure(this, this.getBase() + '/config/log4js.json');
+ }
};
/**
@@ -167,9 +167,9 @@ Application.configLogger = function() {
* @memberOf Application
*/
Application.filter = function (filter) {
- this.before(filter);
- this.after(filter);
- return this;
+ this.before(filter);
+ this.after(filter);
+ return this;
};
/**
@@ -180,13 +180,13 @@ Application.filter = function (filter) {
* @memberOf Application
*/
Application.before = function (bf) {
- var befores = this.get('__befores__');
- if(!befores) {
- befores = [];
- this.set('__befores__', befores);
- }
- befores.push(bf);
- return this;
+ var befores = this.get('__befores__');
+ if(!befores) {
+ befores = [];
+ this.set('__befores__', befores);
+ }
+ befores.push(bf);
+ return this;
};
/**
@@ -197,13 +197,13 @@ Application.before = function (bf) {
* @memberOf Application
*/
Application.after = function (af) {
- var afters = this.get('__afters__');
- if(!afters) {
- afters = [];
- this.set('__afters__', afters);
- }
- afters.push(af);
- return this;
+ var afters = this.get('__afters__');
+ if(!afters) {
+ afters = [];
+ this.set('__afters__', afters);
+ }
+ afters.push(af);
+ return this;
};
/**
@@ -212,47 +212,47 @@ Application.after = function (af) {
* @param {String} name (optional) name of the component
* @param {Object} component component instance or factory function of the component
* @param {[type]} opts (optional) construct parameters for the factory function
- * @return {Object} app instance for chain invoke
+ * @return {Object} app instance for chain invoke
*
* @memberOf Application
*/
Application.load = function(name, component, opts) {
- if(typeof name !== 'string') {
- opts = component;
- component = name;
- name = null;
- if(typeof component.name === 'string') {
- name = component.name;
- }
- }
+ if(typeof name !== 'string') {
+ opts = component;
+ component = name;
+ name = null;
+ if(typeof component.name === 'string') {
+ name = component.name;
+ }
+ }
- if(typeof component === 'function') {
- component = component(this, opts);
- }
+ if(typeof component === 'function') {
+ component = component(this, opts);
+ }
- if(!component) {
- // maybe some component no need to join the components management
- logger.info('load empty component');
- return this;
- }
+ if(!component) {
+ // maybe some component no need to join the components management
+ logger.info('load empty component');
+ return this;
+ }
- if(!name && typeof component.name === 'string') {
- name = component.name;
- }
+ if(!name && typeof component.name === 'string') {
+ name = component.name;
+ }
- if(name && this.components[name]) {
- // ignore duplicat component
- logger.warn('ignore duplicate component: %j', name);
- return;
- }
+ if(name && this.components[name]) {
+ // ignore duplicat component
+ logger.warn('ignore duplicate component: %j', name);
+ return;
+ }
- this.loaded.push(component);
- if(name) {
- // components with a name would get by name throught app.components later.
- this.components[name] = component;
- }
+ this.loaded.push(component);
+ if(name) {
+ // components with a name would get by name throught app.components later.
+ this.components[name] = component;
+ }
- return this;
+ return this;
};
/**
@@ -260,28 +260,28 @@ Application.load = function(name, component, opts) {
*
* Examples:
*
- * app.route('area', routeFunc);
+ * app.route('area', routeFunc);
*
- * var routeFunc = function(session, msg, app, cb) {
- * // all request to area would be route to the first area server
- * var areas = app.getServersByType('area');
- * cb(null, areas[0].id);
- * };
+ * var routeFunc = function(session, msg, app, cb) {
+ * // all request to area would be route to the first area server
+ * var areas = app.getServersByType('area');
+ * cb(null, areas[0].id);
+ * };
*
* @param {String} serverType server type string
* @param {Function} routeFunc route function. routeFunc(session, msg, app, cb)
- * @return {Object} current application instance for chain invoking
+ * @return {Object} current application instance for chain invoking
*
* @memberOf Application
*/
Application.route = function(serverType, routeFunc) {
- var routes = this.get('__routes__');
- if(!routes) {
- routes = {};
- this.set('__routes__', routes);
- }
- routes[serverType] = routeFunc;
- return this;
+ var routes = this.get('__routes__');
+ if(!routes) {
+ routes = {};
+ this.set('__routes__', routes);
+ }
+ routes[serverType] = routeFunc;
+ return this;
};
/**
@@ -292,16 +292,16 @@ Application.route = function(serverType, routeFunc) {
* @memberOf Application
*/
Application.start = function(cb) {
- if(this.state > STATE_INITED) {
- utils.invokeCallback(cb, new Error('application has already start.'));
- return;
- }
- this.loadDefaultComponents();
- var self = this;
- this._optComponents('start', function(err) {
- self.state = STATE_START;
- utils.invokeCallback(cb, err);
- });
+ if(this.state > STATE_INITED) {
+ utils.invokeCallback(cb, new Error('application has already start.'));
+ return;
+ }
+ this.loadDefaultComponents();
+ var self = this;
+ this._optComponents('start', function(err) {
+ self.state = STATE_START;
+ utils.invokeCallback(cb, err);
+ });
};
/**
@@ -311,16 +311,16 @@ Application.start = function(cb) {
* @return {Void}
*/
Application.afterStart = function(cb) {
- if(this.state !== STATE_START) {
- utils.invokeCallback(cb, new Error('application is not running now.'));
- return;
- }
+ if(this.state !== STATE_START) {
+ utils.invokeCallback(cb, new Error('application is not running now.'));
+ return;
+ }
- var self = this;
- this._optComponents('afterStart', function(err) {
- self.state = STATE_STARTED;
- utils.invokeCallback(cb, err);
- });
+ var self = this;
+ this._optComponents('afterStart', function(err) {
+ self.state = STATE_STARTED;
+ utils.invokeCallback(cb, err);
+ });
};
/**
@@ -329,41 +329,41 @@ Application.afterStart = function(cb) {
* @param {Boolean} force whether stop the app immediately
*/
Application.stop = function(force) {
- if(this.state > STATE_STARTED) {
- logger.warn('[pomelo application] application is not running now.');
- return;
- }
- this.state = STATE_STOPED;
- stopComps(this.loaded, 0, force, function() {
- if(force) {
- process.exit(0);
- }
- });
+ if(this.state > STATE_STARTED) {
+ logger.warn('[pomelo application] application is not running now.');
+ return;
+ }
+ this.state = STATE_STOPED;
+ stopComps(this.loaded, 0, force, function() {
+ if(force) {
+ process.exit(0);
+ }
+ });
};
/**
* Stop components.
*
- * @param {Array} comps component list
+ * @param {Array} comps component list
* @param {Number} index current component index
* @param {Boolean} force whether stop component immediately
* @param {Function} cb
*/
var stopComps = function(comps, index, force, cb) {
- if(index >= comps.length) {
- cb();
- return;
- }
- var comp = comps[index];
- if(typeof comp.stop === 'function') {
- comp.stop(force, function() {
- // ignore any error
- stopComps(comps, index +1, force, cb);
- });
- } else {
- stopComps(comps, index +1, force, cb);
- }
+ if(index >= comps.length) {
+ cb();
+ return;
+ }
+ var comp = comps[index];
+ if(typeof comp.stop === 'function') {
+ comp.stop(force, function() {
+ // ignore any error
+ stopComps(comps, index +1, force, cb);
+ });
+ } else {
+ stopComps(comps, index +1, force, cb);
+ }
};
/**
@@ -376,20 +376,20 @@ var stopComps = function(comps, index, force, cb) {
* @api private
*/
Application._optComponents = function(method, cb) {
- var i = 0;
- async.forEachSeries(this.loaded, function(comp, done) {
- i++;
- if(typeof comp[method] === 'function') {
- comp[method](done);
- } else {
- done();
- }
- }, function(err) {
- if(err) {
- logger.error('[pomelo application] fail to operate component, method:%s, err:' + err.stack, method);
- }
- cb(err);
- });
+ var i = 0;
+ async.forEachSeries(this.loaded, function(comp, done) {
+ i++;
+ if(typeof comp[method] === 'function') {
+ comp[method](done);
+ } else {
+ done();
+ }
+ }, function(err) {
+ if(err) {
+ logger.error('[pomelo application] fail to operate component, method:%s, err:' + err.stack, method);
+ }
+ cb(err);
+ });
};
/**
@@ -397,13 +397,13 @@ Application._optComponents = function(method, cb) {
*
* Example:
*
- * app.set('key1', 'value1');
- * app.get('key1'); // 'value1'
- * app.key1; // undefined
+ * app.set('key1', 'value1');
+ * app.get('key1'); // 'value1'
+ * app.key1; // undefined
*
- * app.set('key2', 'value2', true);
- * app.get('key2'); // 'value2'
- * app.key2; // 'value2'
+ * app.set('key2', 'value2', true);
+ * app.get('key2'); // 'value2'
+ * app.key2; // 'value2'
*
* @param {String} setting the setting of application
* @param {String} val the setting's value
@@ -413,14 +413,14 @@ Application._optComponents = function(method, cb) {
* @memberOf Application
*/
Application.set = function (setting, val, attach) {
- if (arguments.length === 1) {
- return this.settings[setting];
- }
- this.settings[setting] = val;
- if(attach) {
- this[setting] = val;
- }
- return this;
+ if (arguments.length === 1) {
+ return this.settings[setting];
+ }
+ this.settings[setting] = val;
+ if(attach) {
+ this[setting] = val;
+ }
+ return this;
};
/**
@@ -432,7 +432,7 @@ Application.set = function (setting, val, attach) {
* @memberOf Application
*/
Application.get = function (setting) {
- return this.settings[setting];
+ return this.settings[setting];
};
/**
@@ -445,12 +445,12 @@ Application.get = function (setting) {
* @memberOf Application
*/
Application.loadConfig = function (key, val) {
- var env = this.get('env');
- val = require(val);
- if (val[env]) {
- val = val[env];
- }
- this.set(key, val);
+ var env = this.get('env');
+ val = require(val);
+ if (val[env]) {
+ val = val[env];
+ }
+ this.set(key, val);
};
/**
@@ -461,7 +461,7 @@ Application.loadConfig = function (key, val) {
* @memberOf Application
*/
Application.enabled = function (setting) {
- return !!this.get(setting);
+ return !!this.get(setting);
};
/**
@@ -472,7 +472,7 @@ Application.enabled = function (setting) {
* @memberOf Application
*/
Application.disabled = function (setting) {
- return !this.get(setting);
+ return !this.get(setting);
};
/**
@@ -483,7 +483,7 @@ Application.disabled = function (setting) {
* @memberOf Application
*/
Application.enable = function (setting) {
- return this.set(setting, true);
+ return this.set(setting, true);
};
/**
@@ -494,7 +494,7 @@ Application.enable = function (setting) {
* @memberOf Application
*/
Application.disable = function (setting) {
- return this.set(setting, false);
+ return this.set(setting, false);
};
/**
@@ -505,17 +505,17 @@ Application.disable = function (setting) {
*
* Examples:
*
- * app.configure(function(){
- * // executed for all envs and server types
- * });
+ * app.configure(function(){
+ * // executed for all envs and server types
+ * });
*
- * app.configure('development', function(){
- * // executed development env
- * });
+ * app.configure('development', function(){
+ * // executed development env
+ * });
*
- * app.configure('development', 'connector', function(){
- * // executed for development env and connector server type
- * });
+ * app.configure('development', 'connector', function(){
+ * // executed for development env and connector server type
+ * });
*
* @param {String} env application environment
* @param {Function} fn callback function
@@ -524,24 +524,24 @@ Application.disable = function (setting) {
* @memberOf Application
*/
Application.configure = function (env, type, fn) {
- var args = [].slice.call(arguments);
- fn = args.pop();
- env = 'all';
- type = 'all';
+ var args = [].slice.call(arguments);
+ fn = args.pop();
+ env = 'all';
+ type = 'all';
- if(args.length > 0) {
- env = args[0];
- }
- if(args.length > 1) {
- type = args[1];
- }
+ if(args.length > 0) {
+ env = args[0];
+ }
+ if(args.length > 1) {
+ type = args[1];
+ }
- if (env === 'all' || env.indexOf(this.settings.env) >= 0) {
- if (type === 'all' || type.indexOf(this.settings.serverType) >= 0) {
- fn.call(this);
- }
- }
- return this;
+ if (env === 'all' || env.indexOf(this.settings.env) >= 0) {
+ if (type === 'all' || type.indexOf(this.settings.serverType) >= 0) {
+ fn.call(this);
+ }
+ }
+ return this;
};
/**
@@ -552,7 +552,7 @@ Application.configure = function (env, type, fn) {
* @memberOf Application
*/
Application.getServers = function() {
- return this.get('__serverMap__');
+ return this.get('__serverMap__');
};
/**
@@ -564,47 +564,47 @@ Application.getServers = function() {
* @memberOf Application
*/
Application.getServerById = function(serverId) {
- return this.get('__serverMap__')[serverId];
+ return this.get('__serverMap__')[serverId];
};
/**
* Get server infos by server type.
*
* @param {String} serverType server type
- * @return {Array} server info list
+ * @return {Array} server info list
*
* @memberOf Application
*/
Application.getServersByType = function(serverType) {
- return this.get('servers')[serverType];
+ return this.get('servers')[serverType];
};
/**
* Check the server whether is a frontend server
*
* @param {server} server server info. it would check current server
- * if server not specified
+ * if server not specified
* @return {Boolean}
*
* @memberOf Application
*/
Application.isFrontend = function(server) {
- server = server || Application.get('curServer');
- return !!server && !!server.wsPort;
+ server = server || Application.get('curServer');
+ return !!server && !!server.wsPort;
};
/**
* Check the server whether is a backend server
*
* @param {server} server server info. it would check current server
- * if server not specified
+ * if server not specified
* @return {Boolean}
*
* @memberOf Application
*/
Application.isBackend = function(server) {
- server = server || Application.get('curServer');
- return !!server && !server.wsPort;
+ server = server || Application.get('curServer');
+ return !!server && !server.wsPort;
};
/**
@@ -615,7 +615,7 @@ Application.isBackend = function(server) {
* @memberOf Application
*/
Application.isMaster = function() {
- return Application.serverType === 'master';
+ return Application.serverType === 'master';
};
/**
@@ -628,17 +628,17 @@ Application.isMaster = function() {
* @memberOf Application
*/
Application.registerAdmin = function(moduleId, module, opts){
- var modules = this.get('__modules__');
- if(!modules) {
- modules = [];
- this.set('__modules__', modules);
- }
-
- if(typeof moduleId !== 'string') {
- opts = module;
- module = moduleId;
- moduleId = module.moduleId;
- }
-
- modules.push({moduleId: moduleId, module: module, opts: opts});
+ var modules = this.get('__modules__');
+ if(!modules) {
+ modules = [];
+ this.set('__modules__', modules);
+ }
+
+ if(typeof moduleId !== 'string') {
+ opts = module;
+ module = moduleId;
+ moduleId = module.moduleId;
+ }
+
+ modules.push({moduleId: moduleId, module: module, opts: opts});
};
36 lib/common/remote/backend/msgRemote.js
View
@@ -3,11 +3,11 @@
* Receive and process request message that forward from frontend server.
*/
module.exports = function(app) {
- return new Remote(app);
+ return new Remote(app);
};
var Remote = function(app) {
- this.app = app;
+ this.app = app;
};
/**
@@ -18,24 +18,24 @@ var Remote = function(app) {
* @param cb {Function} callback function
*/
Remote.prototype.forwardMessage = function(msg, session, cb) {
- var server = this.app.components.__server__;
- var sessionService = this.app.components.__localSession__;
+ var server = this.app.components.__server__;
+ var sessionService = this.app.components.__localSession__;
- if(!server) {
- cb(new Error('server component not enable'));
- return;
- }
+ if(!server) {
+ cb(new Error('server component not enable'));
+ return;
+ }
- if(!sessionService) {
- cb(new Error('local session component not enable'));
- return;
- }
+ if(!sessionService) {
+ cb(new Error('local session component not enable'));
+ return;
+ }
- // generate local session for current request
- var lsession = sessionService.create(session);
+ // generate local session for current request
+ var lsession = sessionService.create(session);
- // handle the request
- server.handle(msg, lsession, function(err, resp) {
- cb(err, resp);
- });
+ // handle the request
+ server.handle(msg, lsession, function(err, resp) {
+ cb(err, resp);
+ });
};
56 lib/common/remote/frontend/channelRemote.js
View
@@ -1,28 +1,28 @@
-/**
- * Remote channel service for frontend server.
- * Receive push request from backend servers and push it to clients.
- */
-var logger = require('pomelo-logger').getLogger(__filename);
-
-module.exports = function(app) {
- return new Remote(app);
-};
-
-var Remote = function(app) {
- this.app = app;
-};
-
-/**
- * Push message to client by uids
- *
- * @param msg {Object} message that would be push to clients
- * @param uids {Array} user ids that would receive the message
- * @param cb {Function} callback function
- */
-Remote.prototype.pushMessage = function(msg, uids, cb) {
- var sessionService = this.app.get('sessionService');
- for(var i=0, l=uids.length; i<l; i++) {
- sessionService.sendMessageByUid(uids[i], msg);
- }
- cb();
-};
+/**
+ * Remote channel service for frontend server.
+ * Receive push request from backend servers and push it to clients.
+ */
+var logger = require('pomelo-logger').getLogger(__filename);
+
+module.exports = function(app) {
+ return new Remote(app);
+};
+
+var Remote = function(app) {
+ this.app = app;
+};
+
+/**
+ * Push message to client by uids
+ *
+ * @param msg {Object} message that would be push to clients
+ * @param uids {Array} user ids that would receive the message
+ * @param cb {Function} callback function
+ */
+Remote.prototype.pushMessage = function(msg, uids, cb) {
+ var sessionService = this.app.get('sessionService');
+ for(var i=0, l=uids.length; i<l; i++) {
+ sessionService.sendMessageByUid(uids[i], msg);
+ }
+ cb();
+};
10 lib/common/remote/frontend/sessionRemote.js
View
@@ -6,21 +6,21 @@ var logger = require('pomelo-logger').getLogger(__filename);
module.exports = function(app) {
- return new Remote(app);
+ return new Remote(app);
};
var Remote = function(app) {
- this.app = app;
+ this.app = app;
};
Remote.prototype.bind = function(sid, uid, cb) {
- this.app.get('sessionService').bind(sid, uid, cb);
+ this.app.get('sessionService').bind(sid, uid, cb);
};
Remote.prototype.push = function(sid, key, value, cb) {
- this.app.get('sessionService').import(sid, key, value, cb);
+ this.app.get('sessionService').import(sid, key, value, cb);
};
Remote.prototype.pushAll = function(sid, settings, cb) {
- this.app.get('sessionService').importAll(sid, settings, cb);
+ this.app.get('sessionService').importAll(sid, settings, cb);
};
561 lib/common/service/channelService.js
View
@@ -1,281 +1,280 @@
-var countDownLatch = require('../../util/countDownLatch');
-var utils = require('../../util/utils');
-var logger = require('pomelo-logger').getLogger(__filename);
-var async = require('async');
-
-/**
- * constant
- */
-var DEFAULT_GROUP_ID = 'default';
-
-var ST_INITED = 0;
-var ST_DESTROYED = 1;
-
-/**
- * Create and maintain channels for server local.
- *
- * ChannelService is created by channel component which is a default loaded
- * component of pomelo and channel service would be accessed by `app.get('channelService')`.
- *
- * @class
- * @constructor
- */
-var ChannelService = function(app) {
- this.app = app;
- this.channels = {};
-};
-
-module.exports = ChannelService;
-
-/**
- * Create channel with name.
- *
- * @param {String} name channel's name
- * @memberOf ChannelService
- */
-ChannelService.prototype.createChannel = function(name) {
- if(this.channels[name]) {
- return this.channels[name];
- }
-
- var c = new Channel(name, this);
- this.channels[name] = c;
- return c;
-};
-
-/**
- * Get channel by name.
- *
- * @param {String} name channel's name
- * @param {Boolean} create if true, create channel
- * @return {Channel}
- * @memberOf ChannelService
- */
-ChannelService.prototype.getChannel = function(name, create) {
- var channel = this.channels[name];
- if(!channel && !!create) {
- channel = this.channels[name] = new Channel(name, this);
- }
- return channel;
-};
-
-/**
- * Destroy channel by name.
- *
- * @param {String} name channel name
- * @memberOf ChannelService
- */
-ChannelService.prototype.destroyChannel = function(name) {
- delete this.channels[name];
-};
-
-/**
- * Push message by uids.
- * Group the uids by group. ignore any uid if sid not specified.
- *
- * @param {Object} msg message that would be sent to client
- * @param {Array} uids the receiver info list, [{uid: userId, sid: frontendServerId}]
- * @param {Function} cb cb(err)
- * @memberOf ChannelService
- */
-ChannelService.prototype.pushMessageByUids = function(msg, uids, cb) {
- if(!uids || uids.length === 0) {
- utils.invokeCallback(cb, new Error('uids should not be empty'));
- return;
- }
- var groups = {}, record;
- for(var i=0, l=uids.length; i<l; i++) {
- record = uids[i];
- add(record.uid, record.sid, groups);
- }
-
- sendMessageByGroup(this, msg, groups, cb);
-};
-
-/**
- * Channel maintains the receiver collection for a subject. You can
- * add users into a channel and then broadcast message to them by channel.
- *
- * @class channel
- * @constructor
- */
-var Channel = function(name, service) {
- this.name = name;
- this.groups = {}; // group map for uids. key: sid, value: [uid]
- this.records = {}; // member records. key: uid
- this.__channelService__ = service;
- this.state = ST_INITED;
-};
-
-/**
- * Add user to channel.
- *
- * @param {Number} uid user id
- * @param {String} sid frontend server id which user has connected to
- */
-Channel.prototype.add = function(uid, sid) {
- if(this.state > ST_INITED) {
- return false;
- } else {
- var res = add(uid, sid, this.groups);
- if(res) {
- this.records[uid] = {sid: sid, uid: uid};
- }
- return res;
- }
-};
-
-/**
- * Remove user from channel.
- *
- * @param {Number} uid user id
- * @param {String} sid frontend server id which user has connected to.
- * @return [Boolean] true if success or false if fail
- */
-Channel.prototype.leave = function(uid, sid) {
- delete this.records[uid];
- return deleteFrom(uid, sid, this.groups[sid]);
-};
-
-/**
- * Get channel members.
- *
- * <b>Notice:</b> Heavy operation.
- *
- * @return {Array} channel member uid list
- */
-Channel.prototype.getMembers = function() {
- var res = [];
- if(!this.groups) {
- return res;
- }
-
- var group, i, l;
- for(var sid in this.groups) {
- group = this.groups[sid];
- for(i=0, l=group.length; i<l; i++) {
- res.push(group[i]);
- }
- }
- return res;
-};
-
-/**
- * Get Member info.
- *
- * @param {String} uid user id
- * @return {Object} member info
- */
-Channel.prototype.getMember = function(uid) {
- return this.records[uid];
-};
-
-/**
- * Destroy channel.
- */
-Channel.prototype.destroy = function() {
- this.state = ST_DESTROYED;
- this.__channelService__.destroyChannel(this.name);
-};
-
-/**
- * Push message to all the members in the channel
- *
- * @param {Object} msg message that would be sent to client
- * @param {Functioin} cb callback function
- */
-Channel.prototype.pushMessage = function(msg, cb) {
- if(this.state !== ST_INITED) {
- utils.invokeCallback(new Error('channel not init'));
- return;
- }
- sendMessageByGroup(this.__channelService__, msg, this.groups, cb);
-};
-
-/**
- * add uid and sid into group. ignore any uid that uid not specified.
- *
- * @param uid user id
- * @param sid server id
- * @param groups {Object} grouped uids, , key: sid, value: [uid]
- */
-var add = function(uid, sid, groups) {
- if(!sid) {
- logger.warn('ignore uid %j for sid not specified.', uid);
- return false;
- }
-
- var group = groups[sid];
- if(!group) {
- group = [];
- groups[sid] = group;
- }
-
- group.push(uid);
- return true;
-};
-
-/**
- * delete element from array
- */
-var deleteFrom = function(uid, sid, group) {
- if(!group) {
- return true;
- }
-
- for(var i=0, l=group.length; i<l; i++) {
- if(group[i] === uid) {
- group.splice(i, 1);
- return true;
- }
- }
-
- return false;
-};
-
-/**
- * push message by group
- *
- * @param msg {Object} message that would be sent to client
- * @param groups {Object} grouped uids, , key: sid, value: [uid]
- * @param cb {Function} cb(err)
- *
- * @api private
- */
-var sendMessageByGroup = function(channelService, msg, groups, cb) {
- var app = channelService.app;
- var namespace = 'sys';
- var service = 'channelRemote';
- var method = 'pushMessage';
- var count = utils.size(groups);
- var successFlag = false;
- msg = JSON.stringify(msg);
-
- if(count === 0) {
- // group is empty
- utils.invokeCallback(cb);
- return;
- }
-
- var latch = countDownLatch.createCountDownLatch(count, function(){
- if(!successFlag) {
- utils.invokeCallback(cb, new Error('all uids push message fail'));
- return;
- }
- utils.invokeCallback(cb);
- });
-
- for(var sid in groups) {
- var uids = groups[sid];
- app.rpcInvoke(sid, {namespace: namespace, service: service, method: method, args: [msg, uids]}, function(err) {
- if(err) {
- logger.error('[pushMessage] fail to dispatch msg, err:' + err.stack);
- latch.done();
- return;
- }
- successFlag = true;
- latch.done();
- });
- }
-
-};
+var countDownLatch = require('../../util/countDownLatch');
+var utils = require('../../util/utils');
+var logger = require('pomelo-logger').getLogger(__filename);
+var async = require('async');
+
+/**
+ * constant
+ */
+var DEFAULT_GROUP_ID = 'default';
+
+var ST_INITED = 0;
+var ST_DESTROYED = 1;
+
+/**
+ * Create and maintain channels for server local.
+ *
+ * ChannelService is created by channel component which is a default loaded
+ * component of pomelo and channel service would be accessed by `app.get('channelService')`.
+ *
+ * @class
+ * @constructor
+ */
+var ChannelService = function(app) {
+ this.app = app;
+ this.channels = {};
+};
+
+module.exports = ChannelService;
+
+/**
+ * Create channel with name.
+ *
+ * @param {String} name channel's name
+ * @memberOf ChannelService
+ */
+ChannelService.prototype.createChannel = function(name) {
+ if(this.channels[name]) {
+ return this.channels[name];
+ }
+
+ var c = new Channel(name, this);
+ this.channels[name] = c;
+ return c;
+};
+
+/**
+ * Get channel by name.
+ *
+ * @param {String} name channel's name
+ * @param {Boolean} create if true, create channel
+ * @return {Channel}
+ * @memberOf ChannelService
+ */
+ChannelService.prototype.getChannel = function(name, create) {
+ var channel = this.channels[name];
+ if(!channel && !!create) {
+ channel = this.channels[name] = new Channel(name, this);
+ }
+ return channel;
+};
+
+/**
+ * Destroy channel by name.
+ *
+ * @param {String} name channel name
+ * @memberOf ChannelService
+ */
+ChannelService.prototype.destroyChannel = function(name) {
+ delete this.channels[name];
+};
+
+/**
+ * Push message by uids.
+ * Group the uids by group. ignore any uid if sid not specified.
+ *
+ * @param {Object} msg message that would be sent to client
+ * @param {Array} uids the receiver info list, [{uid: userId, sid: frontendServerId}]
+ * @param {Function} cb cb(err)
+ * @memberOf ChannelService
+ */
+ChannelService.prototype.pushMessageByUids = function(msg, uids, cb) {
+ if(!uids || uids.length === 0) {
+ utils.invokeCallback(cb, new Error('uids should not be empty'));
+ return;
+ }
+ var groups = {}, record;
+ for(var i=0, l=uids.length; i<l; i++) {
+ record = uids[i];
+ add(record.uid, record.sid, groups);
+ }
+
+ sendMessageByGroup(this, msg, groups, cb);
+};
+
+/**
+ * Channel maintains the receiver collection for a subject. You can
+ * add users into a channel and then broadcast message to them by channel.
+ *
+ * @class channel
+ * @constructor
+ */
+var Channel = function(name, service) {
+ this.name = name;
+ this.groups = {}; // group map for uids. key: sid, value: [uid]
+ this.records = {}; // member records. key: uid
+ this.__channelService__ = service;
+ this.state = ST_INITED;
+};
+
+/**
+ * Add user to channel.
+ *
+ * @param {Number} uid user id
+ * @param {String} sid frontend server id which user has connected to
+ */
+Channel.prototype.add = function(uid, sid) {
+ if(this.state > ST_INITED) {
+ return false;
+ } else {
+ var res = add(uid, sid, this.groups);
+ if(res) {
+ this.records[uid] = {sid: sid, uid: uid};
+ }
+ return res;
+ }
+};
+
+/**
+ * Remove user from channel.
+ *
+ * @param {Number} uid user id
+ * @param {String} sid frontend server id which user has connected to.
+ * @return [Boolean] true if success or false if fail
+ */
+Channel.prototype.leave = function(uid, sid) {
+ delete this.records[uid];
+ return deleteFrom(uid, sid, this.groups[sid]);
+};
+
+/**
+ * Get channel members.
+ *
+ * <b>Notice:</b> Heavy operation.
+ *
+ * @return {Array} channel member uid list
+ */
+Channel.prototype.getMembers = function() {
+ var res = [];
+ if(!this.groups) {
+ return res;
+ }
+
+ var group, i, l;
+ for(var sid in this.groups) {
+ group = this.groups[sid];
+ for(i=0, l=group.length; i<l; i++) {
+ res.push(group[i]);
+ }
+ }
+ return res;
+};
+
+/**
+ * Get Member info.
+ *
+ * @param {String} uid user id
+ * @return {Object} member info
+ */
+Channel.prototype.getMember = function(uid) {
+ return this.records[uid];
+};
+
+/**
+ * Destroy channel.
+ */
+Channel.prototype.destroy = function() {
+ this.state = ST_DESTROYED;
+ this.__channelService__.destroyChannel(this.name);
+};
+
+/**
+ * Push message to all the members in the channel
+ *
+ * @param {Object} msg message that would be sent to client
+ * @param {Functioin} cb callback function
+ */
+Channel.prototype.pushMessage = function(msg, cb) {
+ if(this.state !== ST_INITED) {
+ utils.invokeCallback(new Error('channel not init'));
+ return;
+ }
+ sendMessageByGroup(this.__channelService__, msg, this.groups, cb);
+};
+
+/**
+ * add uid and sid into group. ignore any uid that uid not specified.
+ *
+ * @param uid user id
+ * @param sid server id
+ * @param groups {Object} grouped uids, , key: sid, value: [uid]
+ */
+var add = function(uid, sid, groups) {
+ if(!sid) {
+ logger.warn('ignore uid %j for sid not specified.', uid);
+ return false;
+ }
+
+ var group = groups[sid];
+ if(!group) {
+ group = [];
+ groups[sid] = group;
+ }
+
+ group.push(uid);
+ return true;
+};
+
+/**
+ * delete element from array
+ */
+var deleteFrom = function(uid, sid, group) {
+ if(!group) {
+ return true;
+ }
+
+ for(var i=0, l=group.length; i<l; i++) {
+ if(group[i] === uid) {
+ group.splice(i, 1);
+ return true;
+ }
+ }
+
+ return false;
+};
+
+/**
+ * push message by group
+ *
+ * @param msg {Object} message that would be sent to client
+ * @param groups {Object} grouped uids, , key: sid, value: [uid]
+ * @param cb {Function} cb(err)
+ *
+ * @api private
+ */
+var sendMessageByGroup = function(channelService, msg, groups, cb) {
+ var app = channelService.app;
+ var namespace = 'sys';
+ var service = 'channelRemote';
+ var method = 'pushMessage';
+ var count = utils.size(groups);
+ var successFlag = false;
+ msg = JSON.stringify(msg);
+
+ if(count === 0) {
+ // group is empty
+ utils.invokeCallback(cb);
+ return;
+ }
+
+ var latch = countDownLatch.createCountDownLatch(count, function(){
+ if(!successFlag) {
+ utils.invokeCallback(cb, new Error('all uids push message fail'));
+ return;
+ }
+ utils.invokeCallback(cb);
+ });
+
+ for(var sid in groups) {
+ var uids = groups[sid];
+ app.rpcInvoke(sid, {namespace: namespace, service: service, method: method, args: [msg, uids]}, function(err) {
+ if(err) {
+ logger.error('[pushMessage] fail to dispatch msg, err:' + err.stack);
+ latch.done();
+ return;
+ }
+ successFlag = true;
+ latch.done();
+ });
+ }
+};
44 lib/common/service/connectionService.js
View
@@ -3,10 +3,10 @@
* record connection, login count and list
*/
var Service = function(app) {
- this.serverId = app.get('serverId');
- this.connCount = 0;
- this.loginedCount = 0;
- this.logined = {};
+ this.serverId = app.get('serverId');
+ this.connCount = 0;
+ this.loginedCount = 0;
+ this.logined = {};
};
module.exports = Service;
@@ -21,17 +21,17 @@ var pro = Service.prototype;
* @param info {Object} record for logined user
*/
pro.addLoginedUser = function(uid, info) {
- if(!this.logined[uid]) {
- this.loginedCount++;
- }
- this.logined[uid] = info;
+ if(!this.logined[uid]) {
+ this.loginedCount++;
+ }
+ this.logined[uid] = info;
};
/**
* Increase connection count
*/
pro.increaseConnectionCount = function() {
- this.connCount++;
+ this.connCount++;
};
/**
@@ -40,10 +40,10 @@ pro.increaseConnectionCount = function() {
* @param uid {String} user id
*/
pro.removeLoginedUser = function(uid) {
- if(!!this.logined[uid]) {
- this.loginedCount--;
- }
- delete this.logined[uid];
+ if(!!this.logined[uid]) {
+ this.loginedCount--;
+ }
+ delete this.logined[uid];
};
/**
@@ -52,10 +52,10 @@ pro.removeLoginedUser = function(uid) {
* @param uid {String} uid
*/
pro.decreaseConnectionCount = function(uid) {
- this.connCount--;
- if(!!uid) {
- this.removeLoginedUser(uid);
- }
+ this.connCount--;
+ if(!!uid) {
+ this.removeLoginedUser(uid);
+ }
};
/**
@@ -64,10 +64,10 @@ pro.decreaseConnectionCount = function(uid) {
* @return {Object} statistics info
*/
pro.getStatisticsInfo = function() {
- var list = [];
- for(var uid in this.logined) {
- list.push(this.logined[uid]);
- }
+ var list = [];
+ for(var uid in this.logined) {
+ list.push(this.logined[uid]);
+ }
- return {serverId: this.serverId, totalConnCount: this.connCount, loginedCount: this.loginedCount, loginedList: list};
+ return {serverId: this.serverId, totalConnCount: this.connCount, loginedCount: this.loginedCount, loginedList: list};
};
91 lib/common/service/filterService.js
View
@@ -5,8 +5,8 @@ var logger = require('pomelo-logger').getLogger(__filename);
* Register and fire before and after filters.
*/
var Service = function() {
- this.befores = []; // before filters
- this.afters = []; // after filters
+ this.befores = []; // before filters
+ this.afters = []; // after filters
};
module.exports = Service;
@@ -19,7 +19,7 @@ Service.prototype.name = 'filter';
* @param filter {Object|Function} filter instance or filter function.
*/
Service.prototype.before = function(filter){
- this.befores.push(filter);
+ this.befores.push(filter);
};
/**
@@ -28,7 +28,7 @@ Service.prototype.before = function(filter){
* @param filter {Object|Function} filter instance or filter function.
*/
Service.prototype.after = function(filter){
- this.afters.unshift(filter);
+ this.afters.unshift(filter);
};
/**
@@ -44,31 +44,31 @@ Service.prototype.after = function(filter){
* @param cb {Function} cb(err) callback function to invoke next chain node
*/
Service.prototype.beforeFilter = function(msg, session, cb) {
- var index = 0, self = this;
- var next = function(err, resp) {
- if(index >= self.befores.length) {
- // if done
- cb();
- return;
- }
- if(err) {
- // if error
- cb(err, resp);
- return;
- }
+ var index = 0, self = this;
+ var next = function(err, resp) {
+ if(index >= self.befores.length) {
+ // if done
+ cb();
+ return;
+ }
+ if(err) {
+ // if error
+ cb(err, resp);
+ return;
+ }
- var handler = self.befores[index++];
- if(typeof handler === 'function') {
- handler(msg, session, next);
- } else if(typeof handler.before === 'function') {
- handler.before(msg, session, next);
- } else {
- logger.warn('meet invalid before filter, ignore it.');
- next(err);
- }
- }; //end of next
+ var handler = self.befores[index++];
+ if(typeof handler === 'function') {
+ handler(msg, session, next);
+ } else if(typeof handler.before === 'function') {
+ handler.before(msg, session, next);
+ } else {
+ logger.warn('meet invalid before filter, ignore it.');
+ next(err);
+ }
+ }; //end of next
- next();
+ next();
};
/**
@@ -83,25 +83,24 @@ Service.prototype.beforeFilter = function(msg, session, cb) {
* @param cb {Function} cb(err) callback function to invoke next chain node
*/
Service.prototype.afterFilter = function(err, msg, session, resp, cb) {
- var index = 0, self = this;
- function next(err) {
- //if done
- if(index >= self.afters.length) {
- cb(err, resp);
- return;
- }
+ var index = 0, self = this;
+ function next(err) {
+ //if done
+ if(index >= self.afters.length) {
+ cb(err, resp);
+ return;
+ }
- var handler = self.afters[index++];
- if(typeof handler === 'function') {
- handler(err, msg, session, resp, next);
- } else if(typeof handler.after === 'function') {
- handler.after(err, msg, session, resp, next);
- } else {
- logger.error('meet invalid after filter, ignore it.');
- next(err, resp);
- }
- } //end of next
+ var handler = self.afters[index++];
+ if(typeof handler === 'function') {
+ handler(err, msg, session, resp, next);
+ } else if(typeof handler.after === 'function') {
+ handler.after(err, msg, session, resp, next);
+ } else {
+ logger.error('meet invalid after filter, ignore it.');
+ next(err, resp);
+ }
+ } //end of next
- next(err, resp);
+ next(err, resp);
};
-
58 lib/common/service/handlerService.js
View
@@ -10,8 +10,8 @@ var utils = require('../../util/utils');
* @param {Object} handlers handler map
*/
var Service = function(app, handlers) {
- this.app = app;
- this.handlers = handlers || {};
+ this.app = app;
+ this.handlers = handlers || {};
};
module.exports = Service;
@@ -22,25 +22,25 @@ Service.prototype.name = 'handler';
* Handler the request.
*/
Service.prototype.handle = function(routeRecord, msg, session, cb){
- // the request should be processed by current server
- var handler = getHandler(this.handlers, routeRecord);
- if(!handler) {
- logger.error('[handleManager]: fail to find handler for %j', msg.__route__);
- cb(new Error('fail to find handler for ' + msg.__route__));
- return;
- }
- var start = Date.now();
- handler[routeRecord.method](msg, session, function(err,resp){
- var log = {
- route : msg.__route__,
- args : msg,
- time : utils.format(new Date(start)),
- timeUsed : new Date() - start
- };
- forward_logger.info(JSON.stringify(log));
- cb(err,resp);
- });
- return;
+ // the request should be processed by current server
+ var handler = getHandler(this.handlers, routeRecord);
+ if(!handler) {
+ logger.error('[handleManager]: fail to find handler for %j', msg.__route__);
+ cb(new Error('fail to find handler for ' + msg.__route__));
+ return;
+ }
+ var start = Date.now();
+ handler[routeRecord.method](msg, session, function(err,resp){
+ var log = {
+ route : msg.__route__,
+ args : msg,
+ time : utils.format(new Date(start)),
+ timeUsed : new Date() - start
+ };
+ forward_logger.info(JSON.stringify(log));
+ cb(err,resp);
+ });
+ return;
};
/**
@@ -51,12 +51,12 @@ Service.prototype.handle = function(routeRecord, msg, session, cb){
* @return {Object} handler instance if any matchs or null for match fail
*/
var getHandler = function(handlers, routeRecord) {
- var handler = handlers[routeRecord.handler];
- if(!handler) {
- return null;
- }
- if(typeof handler[routeRecord.method] !== 'function') {
- return null;
- }
- return handler;
+ var handler = handlers[routeRecord.handler];
+ if(!handler) {
+ return null;
+ }
+ if(typeof handler[routeRecord.method] !== 'function') {
+ return null;
+ }
+ return handler;
};
88 lib/common/service/localSessionService.js
View
@@ -12,44 +12,44 @@ var EXPORT_INCLUDE_FIELDS = ['id', 'frontendId', 'uid', 'settings'];
* with frontend server.
*/
var LocalSessionService = function(app) {
- this.app = app;
+ this.app = app;
};
module.exports = LocalSessionService;
LocalSessionService.prototype.create = function(opts) {
- if(!opts) {
- throw new Error('opts should not be empty.');
- }
- return new LocalSession(opts, this);
+ if(!opts) {
+ throw new Error('opts should not be empty.');
+ }
+ return new LocalSession(opts, this);
};
LocalSessionService.prototype.bind = function(frontendId, sid, uid, cb) {
- var namespace = 'sys';
- var service = 'sessionRemote';
- var method = 'bind';
- var args = [sid, uid];
- rpcInvoke(this.app, frontendId, namespace, service, method, args, cb);
+ var namespace = 'sys';
+ var service = 'sessionRemote';
+ var method = 'bind';
+ var args = [sid, uid];
+ rpcInvoke(this.app, frontendId, namespace, service, method, args, cb);
};
LocalSessionService.prototype.push = function(frontendId, sid, key, value, cb) {
- var namespace = 'sys';
- var service = 'sessionRemote';
- var method = 'push';
- var args = [sid, key, value];
- rpcInvoke(this.app, frontendId, namespace, service, method, args, cb);
+ var namespace = 'sys';
+ var service = 'sessionRemote';
+ var method = 'push';
+ var args = [sid, key, value];
+ rpcInvoke(this.app, frontendId, namespace, service, method, args, cb);
};
LocalSessionService.prototype.pushAll = function(frontendId, sid, settings, cb) {
- var namespace = 'sys';
- var service = 'sessionRemote';
- var method = 'pushAll';
- var args = [sid, settings];
- rpcInvoke(this.app, frontendId, namespace, service, method, args, cb);
+ var namespace = 'sys';
+ var service = 'sessionRemote';
+ var method = 'pushAll';
+ var args = [sid, settings];
+ rpcInvoke(this.app, frontendId, namespace, service, method, args, cb);
};
var rpcInvoke = function(app, sid, namespace, service, method, args, cb) {
- app.rpcInvoke(sid, {namespace: namespace, service: service, method: method, args: args}, cb);
+ app.rpcInvoke(sid, {namespace: namespace, service: service, method: method, args: args}, cb);
};
/**
@@ -70,11 +70,11 @@ var rpcInvoke = function(app, sid, namespace, service, method, args, cb) {
* @constructor
*/
var LocalSession = function(opts, service) {
- EventEmitter.call(this);
- for(var f in opts) {
- this[f] = opts[f];
- }
- this.__sessionService__ = service;
+ EventEmitter.call(this);
+ for(var f in opts) {
+ this[f] = opts[f];
+ }
+ this.__sessionService__ = service;
};
util.inherits(LocalSession, EventEmitter);
@@ -89,13 +89,13 @@ util.inherits(LocalSession, EventEmitter);
* @memberOf LocalSession
*/
LocalSession.prototype.bind = function(uid, cb) {
- var self = this;
- this.__sessionService__.bind(this, uid, function(err) {
- if(!err) {
- self.uid = uid;
- }
- cb(err);
- });
+ var self = this;
+ this.__sessionService__.bind(this, uid, function(err) {
+ if(!err) {
+ self.uid = uid;
+ }
+ cb(err);
+ });
};
/**
@@ -105,7 +105,7 @@ LocalSession.prototype.bind = function(uid, cb) {
* @param {Object} value value
*/
LocalSession.prototype.set = function(key, value) {
- this.settings[key] = value;
+ this.settings[key] = value;
};
/**
@@ -115,7 +115,7 @@ LocalSession.prototype.set = function(key, value) {
* @return {Object} value
*/
LocalSession.prototype.get = function(key) {
- return this.settings[key];
+ return this.settings[key];
};
/**
@@ -125,7 +125,7 @@ LocalSession.prototype.get = function(key) {
* @param {Function} cb callback function
*/
LocalSession.prototype.push = function(key, cb) {
- this.__sessionService__.push(this.frontendId, this.id, key, this.get(key), cb);
+ this.__sessionService__.push(this.frontendId, this.id, key, this.get(key), cb);
};
/**
@@ -134,7 +134,7 @@ LocalSession.prototype.push = function(key, cb) {
* @param {Function} cb callback function
*/
LocalSession.prototype.pushAll = function(cb) {
- this.__sessionService__.pushAll(this.frontendId, this.id, this.settings, cb);
+ this.__sessionService__.pushAll(this.frontendId, this.id, this.settings, cb);
};
/**
@@ -143,15 +143,15 @@ LocalSession.prototype.pushAll = function(cb) {
* @api private
*/
LocalSession.prototype.export = function() {
- var res = {}, f;
- for(var i=0, l=EXPORT_INCLUDE_FIELDS.length; i<l; i++) {
- f = EXPORT_INCLUDE_FIELDS[i];
- res[f] = this[f];
- }
+ var res = {}, f;
+ for(var i=0, l=EXPORT_INCLUDE_FIELDS.length; i<l; i++) {
+ f = EXPORT_INCLUDE_FIELDS[i];
+ res[f] = this[f];
+ }
- return res;
+ return res;
};
var rpcInvoke = function(app, sid, namespace, service, method, args, cb) {
- app.rpcInvoke(sid, {namespace: namespace, service: service, method: method, args: args}, cb);
+ app.rpcInvoke(sid, {namespace: namespace, service: service, method: method, args: args}, cb);
};
846 lib/common/service/sessionService.js
View
@@ -1,424 +1,424 @@
-var EventEmitter = require('events').EventEmitter;
-var util = require('util');
-var logger = require('pomelo-logger').getLogger(__filename);
-var utils = require('../../util/utils');
-
-var MOCK_INCLUDE_FIELDS = ['id', 'frontendId', 'uid', '__sessionService__'];
-var EXPORT_INCLUDE_FIELDS = ['id', 'frontendId', 'uid', 'settings'];
-
-var ST_INITED = 0;
-var ST_CLOSED = 1;
-
-/**
- * Session service manages the sessions for each client connection.
- *
- * Session service is created by session component and is only
- * <b>available</b> in frontend servers. You can access the service by
- * `app.get('sessionService')` in frontend servers.
- *
- * @param {Object} opts constructor parameters
- * opts.sendDirectly - whether send the request to the client or cache them until next flush.
- * @class
- * @constructor
- */
-var SessionService = function(opts) {
- opts = opts || {};
- this.sendDirectly = opts.sendDirectly;
- this.sessions = {};
- this.uidMap = {};
- this.msgQueues = {};
-};
-
-module.exports = SessionService;
-
-/**
- * Create and return session.
- *
- * @param {Object} opts {key:obj, uid: str, and etc.}
- * @param {Boolean} force whether replace the origin session if it already existed
- * @return {Session}
- *
- * @memberOf SessionService
- * @api private
- */
-SessionService.prototype.create = function(sid, frontendId, socket) {
- var session = new Session(sid, frontendId, socket, this);
- this.sessions[session.id] = session;
-
- return session;
-};
-
-/**
- * Bind the session with a user id.
- *
- * @memberOf SessionService
- * @api private
- */
-SessionService.prototype.bind = function(sid, uid, cb) {
- var session = this.sessions[sid];
-
- if(!session) {
- cb(new Error('session not exist, sid: ' + sid));
- return;
- }
-
- session.bind(uid);
- cb();
-};
-
-/**
- * Get session by id.
- *
- * @param {Number} id The session id
- * @return {Session}
- *
- * @memberOf SessionService
- * @api private
- */
-SessionService.prototype.get = function(sid) {
- return this.sessions[sid];
-};
-
-/**
- * Get session by userId.
- *
- * @param {Number} uid User id associated with the session
- * @return {Session}
- *
- * @memberOf SessionService
- * @api private
- */
-SessionService.prototype.getByUid = function(uid) {
- return this.uidMap[uid];
-};
-
-/**
- * Remove session by key.
- *
- * @param {Number} sid The session id
- *
- * @memberOf SessionService
- * @api private
- */
-SessionService.prototype.remove = function(sid) {
- var session = this.sessions[sid];
- if(session) {
- delete this.sessions[session.id];
- delete this.uidMap[session.uid];
- delete this.msgQueues[session.id];
- }
-};
-
-/**
- * Import the key/value into session.
- *
- * @api private
- */
-SessionService.prototype.import = function(sid, key, value, cb) {
- var session = this.sessions[sid];
- if(!session) {
- utils.invokeCallback(cb, new Error('session not exist, sid: ' + sid));
- return;
- }
- session.set(key, value);
- utils.invokeCallback(cb);
-};
-
-/**
- * Import new value for the existed session.
- *
- * @memberOf SessionService
- * @api private
- */
-SessionService.prototype.importAll = function(sid, settings, cb) {
- var session = this.sessions[sid];
- if(!session) {
- utils.invokeCallback(cb, new Error('session not exist, sid: ' + sid));
- return;
- }
-
- for(var f in settings) {
- session.set(f, settings[f]);
- }
- utils.invokeCallback(cb);
-};
-
-/**
- * Kick a user offline by user id.
- *
- * @param {Number} uid user id asscociated with the session
- * @param {Function} cb callback function
- *
- * @memberOf SessionService
- */
-SessionService.prototype.kick = function(uid, cb) {
- var session = this.getByUid(uid);
-
- if(session) {
- // notify client
- session.__socket__.send({route: 'onKick'});
- process.nextTick(function() {
- session.closed('kick');
- utils.invokeCallback(cb);
- });
- } else {
- process.nextTick(function() {
- utils.invokeCallback(cb);
- });
- }
-};
-
-/**
- * Send message to the client by session id.
- *
- * @param {String} sid session id
- * @param {Object} msg message to send
- *
- * @memberOf SessionService
- * @api private
- */
-SessionService.prototype.sendMessage = function(sid, msg) {
- var session = this.sessions[sid];
-
- if(!session) {
- logger.debug('fail to send message for session not exits');
- return false;
- }
-
- return send(this, session, msg);
-};
-
-/**
- * Send message to the client by user id.
- *
- * @param {String} uid userId
- * @param {Object} msg message to send
- *
- * @memberOf SessionService
- * @api private
- */
-SessionService.prototype.sendMessageByUid = function(uid, msg) {
- var session = this.uidMap[uid];
-
- if(!session) {
- logger.debug('fail to send message by uid for session not exist. uid: %j', uid);
- return false;
- }
-
- return send(this, session, msg);
-};
-
-/**
- * Send message to the client that associated with the session.
- *
- * @api private
- */
-var send = function(service, session, msg) {
- if(service.sendDirectly) {
- session.__socket__.send(encode(msg));
- return true;
- }
-
- var sid = session.id;
- var queue = service.msgQueues[sid];
- if(!queue) {
- queue = [];
- service.msgQueues[sid] = queue;
- }
-
- queue.push(msg);
- return true;
-};
-
-/**
- * Flush messages to clients.
- *
- * @memberOf SessionService
- * @api private
- */
-SessionService.prototype.flush = function() {
- var queues = this.msgQueues, sessions = this.sessions, queue, session;
- for(var sid in queues) {
- queue = queues[sid];
- if(!queue || queue.length === 0) {
- continue;
- }
-
- session = sessions[sid];
- if(session && session.__socket__) {
- session.__socket__.send(encode(queue));
- } else {
- logger.debug('fail to send message for socket not exist.');
- }
-
- delete queues[sid];
- }
-};
-
-/**
- * Session maintains the relationship between client connect and user information.
- * There is a session associated with each client connect. And it should bind to a
- * user id after the client passes the identification.
- *
- * Session is generated in frontend server and should not be access in handler.
- * There is a proxy class called LocalSession in backend servers and MockLocalSession
- * in frontend servers.
- */
-var Session = function(sid, frontendId, socket, service) {
- EventEmitter.call(this);
- this.id = sid; // r
- this.frontendId = frontendId; // r
- this.uid = null; // r
- this.settings = {};
-
- // private
- this.__socket__ = socket;
- this.__sessionService__ = service;
- this.__state__ = ST_INITED;
-};
-
-util.inherits(Session, EventEmitter);
-
-/**
- * Export current session as mock local session.
- */
-Session.prototype.mockLocalSession = function() {
- return new MockLocalSession(this);
-};
-
-/**
- * Bind the session with the the uid.
- *
- * @param {Number} uid User id
- * @api public
- */
-Session.prototype.bind = function(uid) {
- this.__sessionService__.uidMap[uid] = this;
- this.uid = uid;
- this.emit('bind', uid);
-};
-
-/**
- * Set value for the session.
- *
- * @param {String} key session key
- * @param {Object} value session value
- * @api public
- */
-Session.prototype.set = function(key, value) {
- this.settings[key] = value;
-};
-
-/**
- * Get value from the session.
- *
- * @param {String} key session key
- * @return {Object} value associated with session key
- * @api public
- */
-Session.prototype.get = function(key, value) {
- return this.settings[key];
-};
-
-/**
- * Closed callback for the session.
- *
- * @api public
- */
-Session.prototype.closed = function(reason) {
- if(this.__state__ === ST_CLOSED) {
- return;
- }
- this.__state__ = ST_CLOSED;
- this.__sessionService__.remove(this.id);
- this.emit('closed', this.mockLocalSession(), reason);
- this.__socket__.disconnect();
-};
-
-/**
- * Mock local session for frontend server.
- * Local session is used as session in the backend servers(see
- * lib/common/service/mockLocalSession.js).
- */
-var MockLocalSession = function(session) {
- EventEmitter.call(this);
- clone(session, this, MOCK_INCLUDE_FIELDS);
- // deep copy for settings
- this.settings = dclone(session.settings);
- this.__session__ = session;
-};
-
-util.inherits(MockLocalSession, EventEmitter);
-
-MockLocalSession.prototype.bind = function(uid, cb) {
- var self = this;
- this.__sessionService__.bind(this.id, uid, function(err) {
- if(!err) {
- self.uid = uid;
- }
- utils.invokeCallback(cb, err);
- });
-};
-
-MockLocalSession.prototype.set = function(key, value) {
- this.settings[key] = value;
-};
-
-MockLocalSession.prototype.get = function(key) {
- return this.settings[key];
-};