feat: Optimization framework

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
MiaoWoo 2019-03-02 00:29:46 +08:00
parent 72ae1b4b29
commit f98814bf2d
14 changed files with 125 additions and 83 deletions

View File

@ -18,15 +18,16 @@ public class ScriptEngine {
private String root; private String root;
private Object logger; private Object logger;
private MiaoScriptEngine engine; private MiaoScriptEngine engine;
private ScriptEngineManager manager;
public ScriptEngine(String root, Object logger) { public ScriptEngine(String root, Object logger) {
this.root = root; this.root = root;
this.logger = logger; this.logger = logger;
this.manager = new ScriptEngineManager();
} }
@SneakyThrows @SneakyThrows
public void enableEngine() { public void enableEngine() {
ScriptEngineManager manager = new ScriptEngineManager();
this.engine = new MiaoScriptEngine(manager, "nashorn"); this.engine = new MiaoScriptEngine(manager, "nashorn");
this.engine.put("base", new Base()); this.engine.put("base", new Base());
this.engine.put("ScriptEngineContextHolder", this); this.engine.put("ScriptEngineContextHolder", this);
@ -42,7 +43,8 @@ public class ScriptEngine {
@SneakyThrows @SneakyThrows
public void disableEngine() { public void disableEngine() {
engine.invokeFunction("engineDisable"); this.engine.invokeFunction("engineDisable");
this.engine = null;
} }
public MiaoScriptEngine getEngine() { public MiaoScriptEngine getEngine() {

View File

@ -1,3 +1,7 @@
'use strict';
/**
* MiaoScript Chat处理类
*/
/*global Java, base, module, exports, require*/ /*global Java, base, module, exports, require*/
function ChatHandlerDefault() { function ChatHandlerDefault() {
// noinspection JSUnusedGlobalSymbols // noinspection JSUnusedGlobalSymbols
@ -5,6 +9,4 @@ function ChatHandlerDefault() {
this.json(sender, JSON.stringify(raw)); this.json(sender, JSON.stringify(raw));
} }
} }
var ChatHandler = Object.assign(new ChatHandlerDefault(), requireInternal('chat')); exports = module.exports = Object.assign(new ChatHandlerDefault(), requireInternal('chat'));
exports = module.exports = ChatHandler;

View File

@ -1,3 +1,7 @@
'use strict';
/**
* MiaoScript Command处理类
*/
/*global Java, base, module, exports, require*/ /*global Java, base, module, exports, require*/
function CommandHandlerDefault() { function CommandHandlerDefault() {
this.on = function(jsp, name, exec) { this.on = function(jsp, name, exec) {
@ -13,6 +17,4 @@ function CommandHandlerDefault() {
} }
} }
} }
var CommandHandler = Object.assign(new CommandHandlerDefault(), requireInternal('command')); exports = module.exports = Object.assign(new CommandHandlerDefault(), requireInternal('command'));
exports = module.exports = CommandHandler;

View File

@ -1,10 +1,9 @@
'use strict'; 'use strict';
/** /**
* Bukkit 事件相关 * MiaoScript Event处理
*/ */
/*global Java, base, module, exports, require, __FILE__*/ /*global Java, base, module, exports, require, __FILE__*/
function EventHandlerDefault() { function EventHandlerDefault() {
var Thread = Java.type("java.lang.Thread"); var Thread = Java.type("java.lang.Thread");
@ -14,9 +13,6 @@ function EventHandlerDefault() {
this.listenerMap = []; this.listenerMap = [];
this.baseEventDir = ''; this.baseEventDir = '';
// noinspection JSUnusedLocalSymbols
var self = this;
/** /**
* 扫描包 org.bukkit.event 下的所有事件 * 扫描包 org.bukkit.event 下的所有事件
* 映射简写名称 org.bukkit.event.player.PlayerLoginEvent => playerloginevent * 映射简写名称 org.bukkit.event.player.PlayerLoginEvent => playerloginevent
@ -101,7 +97,12 @@ function EventHandlerDefault() {
this.execute = function execute(name, exec, eventCls) { this.execute = function execute(name, exec, eventCls) {
return function execute() { return function execute() {
try { try {
var time = new Date().getTime()
exec(arguments[arguments.length - 1]); exec(arguments[arguments.length - 1]);
var cost = new Date().getTime() - time;
if (cost > 20) {
console.console('§c注意! §6插件 §b%s §6处理 §d%s §6事件 §c耗时 §4%sms !'.format(name, this.class2Name(eventCls), cost))
}
} catch (ex) { } catch (ex) {
console.console('§6插件 §b%s §6处理 §d%s §6事件时发生异常 §4%s'.format(name, this.class2Name(eventCls), ex)); console.console('§6插件 §b%s §6处理 §d%s §6事件时发生异常 §4%s'.format(name, this.class2Name(eventCls), ex));
console.ex(ex); console.ex(ex);
@ -121,9 +122,7 @@ function EventHandlerDefault() {
if (!jsp || !jsp.description || !jsp.description.name) throw new TypeError('插件名称为空 请检查传入参数!'); if (!jsp || !jsp.description || !jsp.description.name) throw new TypeError('插件名称为空 请检查传入参数!');
var name = jsp.description.name; var name = jsp.description.name;
var eventCls = this.name2Class(name, event); var eventCls = this.name2Class(name, event);
if (!eventCls) { if (!eventCls) { return; }
return;
}
if (typeof priority === 'boolean') { if (typeof priority === 'boolean') {
ignoreCancel = priority; ignoreCancel = priority;
priority = 'NORMAL'; priority = 'NORMAL';
@ -146,7 +145,7 @@ function EventHandlerDefault() {
}; };
listenerMap[name].push(off); listenerMap[name].push(off);
// noinspection JSUnresolvedVariable // noinspection JSUnresolvedVariable
console.debug('插件 %s 注册事件 %s => %s'.format(name, this.class2Name(eventCls), exec.name === '' ? '匿名方法' : exec.name)); console.debug('插件 %s 注册事件 %s => %s'.format(name, this.class2Name(eventCls), exec.name || '匿名方法'));
return off; return off;
} }
} }

View File

@ -1,2 +1,9 @@
'use strict';
/**
* MiaoScript Item处理类
*/
/*global Java, base, module, exports, require*/ /*global Java, base, module, exports, require*/
module.exports = requireInternal('item'); /*global Java, base, module, exports, require*/
function ItemHandlerDefault() {
}
exports = module.exports = Object.assign(new ItemHandlerDefault(), requireInternal('item'));;

View File

@ -1,2 +1,8 @@
'use strict';
/**
* MiaoScript Permission处理类
*/
/*global Java, base, module, exports, require*/ /*global Java, base, module, exports, require*/
module.exports = requireInternal('permission', {warnNotFound: false}); function PermissionHandlerDefault() {
}
exports = module.exports = Object.assign(new PermissionHandlerDefault(), requireInternal('permission', true));

View File

@ -1,7 +1,6 @@
'use strict'; 'use strict';
/** /**
* MiaoScript脚本插件加载类 * MiaoScript脚本插件加载类
* @namespace plugin.configFile.parentFile, command.enable, permission.enable
*/ */
/*global Java, module, exports, require, __FILE__*/ /*global Java, module, exports, require, __FILE__*/
var fs = require('core/fs'); var fs = require('core/fs');
@ -68,20 +67,20 @@ function loadJsPlugins(files) {
files.filter(function filterJsPlugin(file) { files.filter(function filterJsPlugin(file) {
return file.name.endsWith(".js") return file.name.endsWith(".js")
}).forEach(function loadJsPlugin(file) { }).forEach(function loadJsPlugin(file) {
loadPlugin(file)
})
}
function loadPlugin(file) {
try { try {
var plugin = readPlugin(file); loadPlugin(file)
initPlugin(plugin);
plugins[plugin.description.name] = plugin;
return plugin
} catch (ex) { } catch (ex) {
console.console('§6插件 §b%s §6初始化时发生错误 §4%s'.format(file.name, ex.message)); console.console('§6插件 §b%s §6初始化时发生错误 §4%s'.format(file.name, ex.message));
console.ex(ex); console.ex(ex);
} }
})
}
function loadPlugin(file) {
var plugin = readPlugin(file);
initPlugin(plugin);
plugins[plugin.description.name] = plugin;
return plugin
} }
function readPlugin(file) { function readPlugin(file) {
@ -148,10 +147,7 @@ function internalInitPlugin(plugin) {
}; };
// 初始化插件配置相关方法 // 初始化插件配置相关方法
initPluginConfig(plugin); initPluginConfig(plugin);
/** @namespace command.enable */
if (command.enable) command.enable(plugin); if (command.enable) command.enable(plugin);
/** @namespace permission.enable */
if (permission.enable) permission.enable(plugin); if (permission.enable) permission.enable(plugin);
} }
@ -227,7 +223,7 @@ function checkAndGet(args) {
} }
var plugin = exports.plugins[name]; var plugin = exports.plugins[name];
if (!plugin) { if (!plugin) {
throw new Error("插件 " + name + " 不存在!"); throw new Error("插件 " + name + " 不存在!", args);
} }
return [plugin]; return [plugin];
} }
@ -276,9 +272,11 @@ function disable() {
function reloadPlugin(p) { function reloadPlugin(p) {
disable(p); disable(p);
p = loadPlugin(p.__FILE__); p = loadPlugin(p.__FILE__);
if (p) {
load(p); load(p);
enable(p); enable(p);
} }
}
function reload() { function reload() {
checkAndGet(arguments).forEach(reloadPlugin); checkAndGet(arguments).forEach(reloadPlugin);

View File

@ -13,6 +13,4 @@ function ServerHandlerDefault() {
} }
}; };
} }
var ServerHandler = Object.assign(new ServerHandlerDefault(), requireInternal('server')); exports = module.exports = Object.assign(new ServerHandlerDefault(), requireInternal('server'));
exports = module.exports = ServerHandler;

View File

@ -6,6 +6,4 @@
/*global Java, base, module, exports, require*/ /*global Java, base, module, exports, require*/
function TaskHandlerDefault() { function TaskHandlerDefault() {
} }
var TaskHandler = Object.assign(new TaskHandlerDefault(), requireInternal('task')); exports = module.exports = Object.assign(new TaskHandlerDefault(), requireInternal('task'));
exports = module.exports = TaskHandler;

View File

@ -39,26 +39,39 @@
} }
}; };
this.ex = function(message, ex) { this.ex = function(message, ex) {
if (!ex) { switch (toString.call(message)) {
this.console('§4' + message); case "[object String]":
ex = message; message = message + ' ' //message = 'xxxx' ex =Error
} else { break
this.console('§4' + message + ' ' + ex); case "[object Error]":
ex = message // message = Error ex=null
message = ''
break
} }
var track = ex.getStackTrace(); this.console('§4 ' + message + ex)
this.stack(ex).forEach(function(line) {
this.console(line)
})
};
this.stack = function(ex) {
var track = ex ? ex.getStackTrace() : new Error().getStackTrace();
var cache = ['§4' + ex];
if (track.class) { if (track.class) {
track = Arrays.asList(track) track = Arrays.asList(track)
} }
track.forEach(function(stack) { track.forEach(function(stack) {
if (stack.className.startsWith('<')) { if (stack.className.startsWith('<')) {
this.console(' §e位于§c', stack.fileName, '=>§c', stack.methodName, '§4行', stack.lineNumber); var fileName = stack.fileName
fileName = fileName.indexOf('runtime') > -1 ? fileName.split('runtime')[1] : fileName;
cache.push(' §e->§c %s => §4%s:%s'.format(fileName, stack.methodName, stack.lineNumber))
} else {// %s.%s(§4%s:%s§c) } else {// %s.%s(§4%s:%s§c)
var className = stack.className var className = stack.className
className = className.startsWith('jdk.nashorn.internal.scripts') ? className.substr(className.lastIndexOf('$') + 1) : className className = className.startsWith('jdk.nashorn.internal.scripts') ? className.substr(className.lastIndexOf('$') + 1) : className
this.console(' §e位于§c', className + '.' + stack.methodName + '(§4' + stack.fileName + ':' + stack.lineNumber + '§c)'); cache.push(' §e->§c %s.%s(§4%s:%s§c)'.format(className, stack.methodName, stack.fileName, stack.lineNumber));
}
});
return cache;
} }
}.bind(this));
};
}; };
global.Console = ConsoleDefault; global.Console = ConsoleDefault;
})(global); })(global);

View File

@ -15,7 +15,7 @@
loadServerLib(); loadServerLib();
loadPlugins(); loadPlugins();
} catch (ex) { } catch (ex) {
console.console("§4Init plugin system lib failed! ERROR:§c", ex); console.console("§4Initialization plugin system lib failed! ERROR:§c", ex);
console.ex(ex); console.ex(ex);
} }
console.log('MiaoScript engine loading completed... Done (' + (new Date().getTime() - startTime) / 1000 + 's)!'); console.log('MiaoScript engine loading completed... Done (' + (new Date().getTime() - startTime) / 1000 + 's)!');
@ -33,21 +33,6 @@
load(root + '/core/detect.js'); load(root + '/core/detect.js');
} }
/**
* 初始化模块
*/
function loadRequire() {
global.engineLoad = load;
global.load = function __PreventGlobalLoadFunction__() {
throw new Error('Internal engine system not allow use `load` function!');
};
// 初始化加载器
global.require = engineLoad(root + '/core/require.js')(root);
global.requireInternal = function requireInternal(name) {
return require(root + '/internal/' + DetectServerType + '/' + name + '.js', arguments[1]);
}
}
/** /**
* 加载补丁 * 加载补丁
*/ */
@ -62,6 +47,26 @@
}) })
} }
/**
* 初始化模块
*/
function loadRequire() {
global.engineLoad = load;
global.load = function __PreventGlobalLoadFunction__() {
throw new Error('Internal engine system not allow use `load` function!');
};
// 初始化加载器
global.require = engineLoad(root + '/core/require.js')(root);
global.requireInternal = function requireInternal(name) {
try {
return require(root + '/internal/' + DetectServerType + '/' + name + '.js');
} catch (ex) {
if (!arguments[1]) { return {} }
throw ex;
}
}
}
/** /**
* 加载系统类库 * 加载系统类库
*/ */

View File

@ -6,13 +6,19 @@
var sender = arguments[0]; var sender = arguments[0];
if (!(sender instanceof org.bukkit.command.CommandSender)) { if (!(sender instanceof org.bukkit.command.CommandSender)) {
this.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!") this.error("第一个参数未实现 org.bukkit.command.CommandSender 无法发送消息!")
return return;
} }
if (toString.call(arguments[1]) === "[object Array]") {
arguments[1].forEach(function(line) {
sender.sendMessage(this.prefix + line);
}.bind(this))
} else {
var args = Array.prototype.slice.call(arguments, 1); var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(console.prefix + args.join(' ')); sender.sendMessage(this.prefix + args.join(' '));
}; }
}.bind(this);
this.console = function() { this.console = function() {
this.sender(MServer.consoleSender, Array.prototype.join.call(arguments, ' ')); this.sender(MServer.consoleSender, Array.prototype.join.call(arguments, ' '));
}; }.bind(this);
}; };
})(global); })(global);

View File

@ -9,8 +9,14 @@
this.error("第一个参数未实现 org.spongepowered.api.command.CommandSource 无法发送消息!") this.error("第一个参数未实现 org.spongepowered.api.command.CommandSource 无法发送消息!")
return return
} }
if (toString.call(arguments[1]) === "[object Array]") {
arguments[1].forEach(function(line) {
sender.sendMessage(Text.of(this.prefix + line));
}.bind(this))
} else {
var args = Array.prototype.slice.call(arguments, 1); var args = Array.prototype.slice.call(arguments, 1);
sender.sendMessage(Text.of(console.prefix + args.join(' '))); sender.sendMessage(Text.of(this.prefix + args.join(' ')));
}
}; };
this.console = function() { this.console = function() {
this.sender(MServer.server.console, Array.prototype.join.call(arguments, ' ')); this.sender(MServer.server.console, Array.prototype.join.call(arguments, ' '));