feat: 异步加载 polyfill 并且同步加载 @ccms/core

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
MiaoWoo 2021-03-26 15:54:26 +08:00
parent 54e40b6768
commit 1cb4c05efd
9 changed files with 94 additions and 51 deletions

18
pom.xml
View File

@ -1,9 +1,8 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>pw.yumc</groupId> <groupId>pw.yumc</groupId>
<artifactId>MiaoScript</artifactId> <artifactId>MiaoScript</artifactId>
<version>0.10.1</version> <version>0.11.0</version>
<developers> <developers>
<developer> <developer>
<id>502647092</id> <id>502647092</id>
@ -54,10 +53,15 @@
<properties> <properties>
<env.GIT_COMMIT>DEV</env.GIT_COMMIT> <env.GIT_COMMIT>DEV</env.GIT_COMMIT>
<update.changes> <update.changes>
§621-03-25 §afeat: 异步加载 polyfill 并且同步加载 @ccms/core;
§621-03-25 §cfix: 修改 ployfill 为 polyfill;
§620-12-22 §cfix: 增加 require 效验;
§620-12-17 §afeat: JavaScriptTask 新增任务ID 并通过 ID 比较优先级; §620-12-17 §afeat: JavaScriptTask 新增任务ID 并通过 ID 比较优先级;
§620-12-16 §afeat: 优化 require 路径寻找速度; §620-12-16 §afeat: 新增 require 缓存 优化路径寻找速度;
§620-12-15 §cfix: 修复 非主线程重载时发生的异常; §620-12-15 §cfix: 修复 非主线程重载时发生的异常;
§620-12-07 §cfix: 修复 Windows 环境 重载异常; §620-12-07 §cfix: 修复 Windows 环境 重载异常
</update.changes>
<update.changelog>
§620-11-19 §afeat: 新增 JavaScriptTask 类; §620-11-19 §afeat: 新增 JavaScriptTask 类;
§620-11-11 §afeat: 新增 package 版本锁定逻辑; §620-11-11 §afeat: 新增 package 版本锁定逻辑;
§620-09-21 §afeat: 完善 upgrade 逻辑; §620-09-21 §afeat: 完善 upgrade 逻辑;
@ -77,9 +81,7 @@
§620-02-16 §afeat: 新增 Source Map 支持; §620-02-16 §afeat: 新增 Source Map 支持;
§620-02-02 §afeat: 迁移 ployfill 到 @ms/ployfill; §620-02-02 §afeat: 迁移 ployfill 到 @ms/ployfill;
§620-01-14 §afeat: 新增 Bungee 支持; §620-01-14 §afeat: 新增 Bungee 支持;
      §afeat: 新增 instance 实例获取        §afeat: 新增 instance 实例获取;
</update.changes>
<update.changelog>
§619-09-24 §cremove: 移除 okhttp3 类库; §619-09-24 §cremove: 移除 okhttp3 类库;
      §afeat: 新增require自动下载模块功能;       §afeat: 新增require自动下载模块功能;
§619-09-21 §afeat: 新增 okhttp3 类库; §619-09-21 §afeat: 新增 okhttp3 类库;

View File

@ -15,9 +15,14 @@ public class MiaoScript extends JavaPlugin {
@Override @Override
@SneakyThrows @SneakyThrows
public void onEnable() { public void onLoad() {
Thread.currentThread().setContextClassLoader(getClassLoader()); Thread.currentThread().setContextClassLoader(getClassLoader());
engine = new ScriptEngine(getDataFolder().getCanonicalPath(), getLogger(), this); engine = new ScriptEngine(getDataFolder().getCanonicalPath(), getLogger(), this);
engine.loadEngine();
}
@Override
public void onEnable() {
engine.enableEngine(); engine.enableEngine();
} }

View File

@ -14,9 +14,14 @@ public class MiaoScriptBungee extends Plugin {
@Override @Override
@SneakyThrows @SneakyThrows
public void onEnable() { public void onLoad() {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
engine = new ScriptEngine(getDataFolder().getCanonicalPath(), getLogger(), this); engine = new ScriptEngine(getDataFolder().getCanonicalPath(), getLogger(), this);
engine.loadEngine();
}
@Override
public void onEnable() {
engine.enableEngine(); engine.enableEngine();
} }

View File

@ -11,12 +11,17 @@ public class MiaoScriptNukkit extends PluginBase {
@Override @Override
@SneakyThrows @SneakyThrows
public void onEnable() { public void onLoad() {
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
engine = new ScriptEngine(getDataFolder().getCanonicalPath(), getLogger(), this); engine = new ScriptEngine(getDataFolder().getCanonicalPath(), getLogger(), this);
engine.enableEngine(); engine.enableEngine();
} }
@Override
public void onEnable() {
engine.enableEngine();
}
@Override @Override
public void onDisable() { public void onDisable() {
engine.disableEngine(); engine.disableEngine();

View File

@ -7,6 +7,7 @@ import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.GameReloadEvent; import org.spongepowered.api.event.game.GameReloadEvent;
import org.spongepowered.api.event.game.state.GameStartedServerEvent; import org.spongepowered.api.event.game.state.GameStartedServerEvent;
import org.spongepowered.api.event.game.state.GameStartingServerEvent;
import org.spongepowered.api.event.game.state.GameStoppingServerEvent; import org.spongepowered.api.event.game.state.GameStoppingServerEvent;
import org.spongepowered.api.plugin.Plugin; import org.spongepowered.api.plugin.Plugin;
@ -31,8 +32,14 @@ public class MiaoScriptSponge {
@Listener @Listener
@SneakyThrows @SneakyThrows
public void onStart(GameStartedServerEvent event) { public void onStarting(GameStartingServerEvent event) {
engine = new ScriptEngine(pluginConfigDir.getCanonicalPath(), logger, this); engine = new ScriptEngine(pluginConfigDir.getCanonicalPath(), logger, this);
engine.loadEngine();
}
@Listener
@SneakyThrows
public void onStart(GameStartedServerEvent event) {
engine.enableEngine(); engine.enableEngine();
} }

View File

@ -6,6 +6,10 @@ import javax.script.ScriptEngineManager;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
/** /**
* Created with IntelliJ IDEA * Created with IntelliJ IDEA
@ -18,6 +22,7 @@ public class ScriptEngine {
private final String root; private final String root;
private final Base base; private final Base base;
private MiaoScriptEngine engine; private MiaoScriptEngine engine;
private Object future;
public ScriptEngine(String root, Object logger, Object instance) { public ScriptEngine(String root, Object logger, Object instance) {
this.loader = Thread.currentThread().getContextClassLoader(); this.loader = Thread.currentThread().getContextClassLoader();
@ -38,7 +43,7 @@ public class ScriptEngine {
} }
@SneakyThrows @SneakyThrows
public void enableEngine() { public void loadEngine() {
ClassLoader originLoader = Thread.currentThread().getContextClassLoader(); ClassLoader originLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(this.loader); Thread.currentThread().setContextClassLoader(this.loader);
createEngine(); createEngine();
@ -49,10 +54,15 @@ public class ScriptEngine {
} else { } else {
this.engine.eval("load('classpath:bios.js')"); this.engine.eval("load('classpath:bios.js')");
} }
engine.invokeFunction("boot", root, logger); future = engine.invokeFunction("boot", root, logger);
Thread.currentThread().setContextClassLoader(originLoader); Thread.currentThread().setContextClassLoader(originLoader);
} }
@SneakyThrows
public void enableEngine() {
engine.invokeFunction("start", future);
}
@SneakyThrows @SneakyThrows
public void disableEngine() { public void disableEngine() {
synchronized (logger) { synchronized (logger) {

View File

@ -1,41 +1,40 @@
'use strict'; 'use strict'
var global = this; var global = this;
/** /**
* Init MiaoScriptEngine Runtime * Init MiaoScriptEngine Runtime
*/ */
(function () { (function () {
var loader;
global.engineDisable = function () { global.engineDisable = function () {
global.engineDisableImpl && global.engineDisableImpl() global.engineDisableImpl && global.engineDisableImpl()
if (java.nio.file.Files.exists(java.nio.file.Paths.get(root, "old_node_modules"))) { if (java.nio.file.Files.exists(java.nio.file.Paths.get(root, "old_node_modules"))) {
logger.info('Found old_node_modules folder delete...'); logger.info('Found old_node_modules folder delete...')
base.delete(java.nio.file.Paths.get(root, "old_node_modules")) base.delete(java.nio.file.Paths.get(root, "old_node_modules"))
} }
if (java.nio.file.Files.exists(java.nio.file.Paths.get(root, "upgrade"))) { if (java.nio.file.Files.exists(java.nio.file.Paths.get(root, "upgrade"))) {
logger.info('Found upgrade file delete node_modules...'); logger.info('Found upgrade file delete node_modules...')
base.delete(java.nio.file.Paths.get(root, "node_modules")) base.delete(java.nio.file.Paths.get(root, "node_modules"))
base.delete(java.nio.file.Paths.get(root, "upgrade")) base.delete(java.nio.file.Paths.get(root, "upgrade"))
} }
}; }
global.boot = function (root, logger) { global.boot = function (root, logger) {
global.scope = java.lang.System.getenv("MS_NODE_CORE_SCOPE") || "@ccms"; global.scope = java.lang.System.getenv("MS_NODE_CORE_SCOPE") || "@ccms"
global.log = logger; global.log = logger
// Development Env Detect // Development Env Detect
global.root = root || "src/main/resources"; global.root = root || "src/main/resources"
if (__FILE__.indexOf('!') === -1) { if (__FILE__.indexOf('!') === -1) {
logger.info('Loading custom BIOS file ' + __FILE__); logger.info('Loading custom BIOS file ' + __FILE__)
global.debug = true; global.debug = true
} }
if (java.nio.file.Files.exists(java.nio.file.Paths.get(root, "debug"))) { if (java.nio.file.Files.exists(java.nio.file.Paths.get(root, "debug"))) {
logger.info('Running in debug mode...'); logger.info('Running in debug mode...')
global.debug = true; global.debug = true
} }
if (java.nio.file.Files.exists(java.nio.file.Paths.get(root, "level"))) { if (java.nio.file.Files.exists(java.nio.file.Paths.get(root, "level"))) {
global.level = base.read(java.nio.file.Paths.get(root, "level")) global.level = base.read(java.nio.file.Paths.get(root, "level"))
logger.info('Set system level to [' + global.level + ']...'); logger.info('Set system level to [' + global.level + ']...')
} }
if (java.nio.file.Files.exists(java.nio.file.Paths.get(root, "upgrade"))) { if (java.nio.file.Files.exists(java.nio.file.Paths.get(root, "upgrade"))) {
logger.info('Found upgrade file starting upgrade...'); logger.info('Found upgrade file starting upgrade...')
base.move(java.nio.file.Paths.get(root, "node_modules"), java.nio.file.Paths.get(root, "old_node_modules")) base.move(java.nio.file.Paths.get(root, "node_modules"), java.nio.file.Paths.get(root, "old_node_modules"))
base.delete(java.nio.file.Paths.get(root, "upgrade")) base.delete(java.nio.file.Paths.get(root, "upgrade"))
} }
@ -46,27 +45,37 @@ var global = this;
} }
}, "MiaoScript node_modules clean thread").start() }, "MiaoScript node_modules clean thread").start()
// Check Class Loader, Sometimes Server will can't found plugin.yml file // Check Class Loader, Sometimes Server will can't found plugin.yml file
loader = checkClassLoader(); var loader = checkClassLoader()
var future = new java.util.concurrent.FutureTask(function () {
java.lang.Thread.currentThread().contextClassLoader = loader
load(java.lang.System.getenv("MS_NODE_CORE_POLYFILL") || 'classpath:core/polyfill.js')(root, logger)
})
// Async Loading MiaoScript Engine // Async Loading MiaoScript Engine
new java.lang.Thread(function () { new java.lang.Thread(future, "MiaoScript thread").start()
java.lang.Thread.currentThread().contextClassLoader = loader; return future
load(java.lang.System.getenv("MS_NODE_CORE_PLOYFILL") || 'classpath:core/ployfill.js')(root, logger); }
global.engineDisableImpl = require(java.lang.System.getenv("MS_NODE_CORE_MODULE") || global.scope + '/core').default || function () {
global.start = function (future) {
if (!future.isDone()) {
logger.info("Waiting MiaoScript booted...")
future.get()
}
logger.info("MiaoScript booted starting...")
global.engineDisableImpl = require(java.lang.System.getenv("MS_NODE_CORE_MODULE") || (global.scope + '/core')).default || function () {
logger.info('Error: abnormal Initialization MiaoScript Engine. Skip disable step...') logger.info('Error: abnormal Initialization MiaoScript Engine. Skip disable step...')
}; }
}, "MiaoScript thread").start() }
};
function checkClassLoader() { function checkClassLoader() {
var classLoader = java.lang.Thread.currentThread().contextClassLoader; var classLoader = java.lang.Thread.currentThread().contextClassLoader
if (classLoader.getResource("bios.js") === null) { if (classLoader.getResource("bios.js") === null) {
throw Error("Error class loader: " + classLoader.class.name + " Please contact the author MiaoWoo!"); throw Error("Error class loader: " + classLoader.class.name + " Please contact the author MiaoWoo!")
} else { } else {
log.info("Class loader compatible: " + classLoader.class.name); log.info("Class loader compatible: " + classLoader.class.name)
if (classLoader.parent) { if (classLoader.parent) {
log.info("Parent class loader: " + classLoader.parent.class.name); log.info("Parent class loader: " + classLoader.parent.class.name)
} }
} }
return classLoader; return classLoader
} }
})(); })()

View File

@ -23,6 +23,6 @@
global.console = engineLoad(java.lang.System.getenv("MS_NODE_CORE_CONSOLE") || 'classpath:core/console.js')(logger); global.console = engineLoad(java.lang.System.getenv("MS_NODE_CORE_CONSOLE") || 'classpath:core/console.js')(logger);
console.log("Loading Engine at Thread", java.lang.Thread.currentThread().name) console.log("Loading Engine at Thread", java.lang.Thread.currentThread().name)
global.require = engineLoad(java.lang.System.getenv("MS_NODE_CORE_REQUIRE") || 'classpath:core/require.js')(root); global.require = engineLoad(java.lang.System.getenv("MS_NODE_CORE_REQUIRE") || 'classpath:core/require.js')(root);
require(global.scope + '/ployfill') require(global.scope + '/polyfill')
} }
) )

View File

@ -384,7 +384,6 @@
if ((file = resolve(name, path, optional)) === undefined) { if ((file = resolve(name, path, optional)) === undefined) {
// excloud local dir, prevent too many recursive call and cache not found module // excloud local dir, prevent too many recursive call and cache not found module
if (optional.local || optional.recursive || notFoundModules[name]) { if (optional.local || optional.recursive || notFoundModules[name]) {
console.log(name, path, optional, notFoundModules[name])
throw new Error("Can't found module " + name + '(' + JSON.stringify(optional) + ') at local ' + path + ' or network!') throw new Error("Can't found module " + name + '(' + JSON.stringify(optional) + ') at local ' + path + ' or network!')
} }
try { try {
@ -430,16 +429,17 @@
* @param {any} optional * @param {any} optional
*/ */
return function __DynamicRequire__(path, optional) { return function __DynamicRequire__(path, optional) {
if (!path) { throw new Error('require path can\'t be undefined or empty!') }
return _require(path, parent, __assign({ cache: true, parentId: parentId, parent: parent, path: path, local: path.startsWith('.') || path.startsWith('/') }, optional)).exports return _require(path, parent, __assign({ cache: true, parentId: parentId, parent: parent, path: path, local: path.startsWith('.') || path.startsWith('/') }, optional)).exports
} }
} }
/** /**
* @param {string} name * @param {string} path
* @param {any} optional 附加选项 * @param {any} optional 附加选项
*/ */
function __DynamicResolve__(name, optional) { function __DynamicResolve__(path, optional) {
return _canonical(new File(resolve(name, parent, __assign({ cache: true, parent: parent, local: name.startsWith('.') || name.startsWith('/') }, optional)))) return _canonical(new File(resolve(path, parent, __assign({ cache: true, parent: parent, local: path.startsWith('.') || path.startsWith('/') }, optional))))
} }
/** /**