Add core detection and scheduler adapters
This commit is contained in:
1 parent
f06ad804a5
commit
06a4e67e80
28 files changed
+1440
-2
No files matched your search
@@ -0,0 +1,69 @@
|
||||
package dev.itxiaohui.contentguard.probe;
|
||||
|
||||
import dev.itxiaohui.contentguard.ContentGuardPlugin;
|
||||
import dev.itxiaohui.contentguard.core.ServerScheduler;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.ConsoleCommandSender;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
public final class CompatibilityProbePlugin extends JavaPlugin implements Listener {
|
||||
private ServerScheduler scheduler;
|
||||
private boolean folia;
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
var plugin = (ContentGuardPlugin) getServer().getPluginManager().getPlugin("ItxiaohuiContentGuard");
|
||||
var compatibility = plugin.compatibility();
|
||||
scheduler = compatibility.scheduler();
|
||||
folia = compatibility.info().folia();
|
||||
getServer().getPluginManager().registerEvents(this, this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (!(sender instanceof ConsoleCommandSender)) {
|
||||
return true;
|
||||
}
|
||||
scheduler.async(() -> result("async", !Bukkit.isPrimaryThread()));
|
||||
scheduler.global(() -> {
|
||||
result("global", folia ? paperBoolean("isGlobalTickThread", new Class<?>[0]) : Bukkit.isPrimaryThread());
|
||||
World world = getServer().getWorlds().getFirst();
|
||||
scheduler.region(world, 0, 0, () -> result("region",
|
||||
folia ? paperBoolean("isOwnedByCurrentRegion",
|
||||
new Class<?>[]{World.class, int.class, int.class}, world, 0, 0) : Bukkit.isPrimaryThread()));
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onJoin(PlayerJoinEvent event) {
|
||||
var player = event.getPlayer();
|
||||
var cancelled = scheduler.entity(player, () -> result("cancelled-task-ran", false),
|
||||
() -> result("cancelled-task-retired", false));
|
||||
result("entity-cancel", cancelled.cancel());
|
||||
scheduler.entity(player, () -> result("entity",
|
||||
player.isOnline() && (folia ? paperBoolean("isOwnedByCurrentRegion",
|
||||
new Class<?>[]{Entity.class}, player) : Bukkit.isPrimaryThread())),
|
||||
() -> result("entity-retired-unexpectedly", false));
|
||||
}
|
||||
|
||||
private boolean paperBoolean(String method, Class<?>[] types, Object... args) {
|
||||
try {
|
||||
return (boolean) Bukkit.class.getMethod(method, types).invoke(null, args);
|
||||
} catch (ReflectiveOperationException failure) {
|
||||
getLogger().severe("ICG_PROBE method=" + method + " error=" + failure);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void result(String name, boolean passed) {
|
||||
getLogger().info("ICG_PROBE " + name + "=" + passed + " thread=" + Thread.currentThread().getName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
name: ICGCompatibilityProbe
|
||||
main: dev.itxiaohui.contentguard.probe.CompatibilityProbePlugin
|
||||
version: '1'
|
||||
api-version: '1.21'
|
||||
folia-supported: true
|
||||
depend: [ItxiaohuiContentGuard]
|
||||
commands:
|
||||
icgprobe:
|
||||
description: Run scheduler compatibility checks from the console
|
||||
@@ -0,0 +1,45 @@
|
||||
package dev.itxiaohui.contentguard;
|
||||
|
||||
import dev.itxiaohui.contentguard.core.CompatibilityManager;
|
||||
import java.util.Objects;
|
||||
import java.util.logging.Level;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
public final class ContentGuardPlugin extends JavaPlugin {
|
||||
private CompatibilityManager compatibility;
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
try {
|
||||
compatibility = CompatibilityManager.initialize(this);
|
||||
} catch (IllegalStateException | LinkageError failure) {
|
||||
getLogger().log(Level.SEVERE, "兼容性检查失败,正在停用插件", failure);
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
return;
|
||||
}
|
||||
getLogger().info(compatibility.info().summary());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (compatibility != null) {
|
||||
compatibility.close();
|
||||
getLogger().info("ICG_LIFECYCLE scheduler=closed");
|
||||
}
|
||||
}
|
||||
|
||||
public CompatibilityManager compatibility() {
|
||||
return Objects.requireNonNull(compatibility, "Compatibility manager is not initialized");
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length == 0 || (args.length == 1 && args[0].equalsIgnoreCase("info"))) {
|
||||
sender.sendMessage(compatibility().info().summary());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package dev.itxiaohui.contentguard.core;
|
||||
|
||||
import java.util.Objects;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
|
||||
final class BukkitSchedulerAdapter extends TrackedScheduler {
|
||||
private final Plugin plugin;
|
||||
private final BukkitScheduler scheduler;
|
||||
|
||||
BukkitSchedulerAdapter(Plugin plugin, BukkitScheduler scheduler) {
|
||||
this.plugin = plugin;
|
||||
this.scheduler = scheduler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Task global(Runnable action) {
|
||||
return submit(action, () -> {}, task -> scheduler.runTask(plugin, task::run)::cancel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Task region(World world, int chunkX, int chunkZ, Runnable action) {
|
||||
Objects.requireNonNull(world, "world");
|
||||
return global(action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Task entity(Entity entity, Runnable action, Runnable retired) {
|
||||
Objects.requireNonNull(entity, "entity");
|
||||
return submit(action, retired, task -> scheduler.runTask(plugin, () -> {
|
||||
boolean active = entity instanceof Player player ? player.isOnline() : entity.isValid();
|
||||
if (active) {
|
||||
task.run();
|
||||
} else {
|
||||
task.retired();
|
||||
}
|
||||
})::cancel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Task async(Runnable action) {
|
||||
return submit(action, () -> {}, task -> scheduler.runTaskAsynchronously(plugin, task::run)::cancel);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package dev.itxiaohui.contentguard.core;
|
||||
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
public record CompatibilityManager(CoreInfo info, ServerScheduler scheduler) implements AutoCloseable {
|
||||
public static CompatibilityManager initialize(Plugin plugin) {
|
||||
CoreDetector.Detection detection = new CoreDetector().inspect(plugin.getServer());
|
||||
ServerScheduler scheduler = switch (detection.adapter()) {
|
||||
case BUKKIT -> new BukkitSchedulerAdapter(plugin, detection.bukkit());
|
||||
case PAPER -> new PaperSchedulerAdapter(plugin, detection.nativeApi());
|
||||
case FOLIA -> new FoliaSchedulerAdapter(plugin, detection.nativeApi());
|
||||
};
|
||||
return new CompatibilityManager(detection.info(), scheduler);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
scheduler.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package dev.itxiaohui.contentguard.core;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Locale;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
|
||||
public final class CoreDetector {
|
||||
enum Adapter {
|
||||
BUKKIT("BukkitSchedulerAdapter"), PAPER("PaperSchedulerAdapter"), FOLIA("FoliaSchedulerAdapter");
|
||||
|
||||
final String className;
|
||||
|
||||
Adapter(String className) {
|
||||
this.className = className;
|
||||
}
|
||||
}
|
||||
|
||||
record Detection(CoreInfo info, Adapter adapter, NativeSchedulerApi nativeApi, BukkitScheduler bukkit) {}
|
||||
private record Brand(String id, String minecraftVersion) {}
|
||||
|
||||
public CoreInfo detect(Server server) {
|
||||
return inspect(server).info();
|
||||
}
|
||||
|
||||
Detection inspect(Server server) {
|
||||
String name = server.getName();
|
||||
String version = server.getVersion();
|
||||
String apiVersion = server.getBukkitVersion();
|
||||
Brand brand = readBrand();
|
||||
boolean paperApi = brand != null || hasClass("io.papermc.paper.event.player.AsyncChatEvent");
|
||||
String reportedCore = identify(brand, name, version);
|
||||
boolean folia = hasClass("io.papermc.paper.threadedregions.RegionizedServer")
|
||||
|| reportedCore.equals("Folia");
|
||||
String core = folia ? "Folia" : reportedCore;
|
||||
NativeSchedulerApi nativeApi = null;
|
||||
BukkitScheduler bukkit = null;
|
||||
Adapter adapter;
|
||||
|
||||
try {
|
||||
nativeApi = NativeSchedulerApi.probe(server);
|
||||
adapter = folia ? Adapter.FOLIA : Adapter.PAPER;
|
||||
} catch (ReflectiveOperationException | LinkageError failure) {
|
||||
if (folia || paperApi || hasNativeSchedulerMethods()) {
|
||||
Throwable cause = failure instanceof InvocationTargetException && failure.getCause() != null
|
||||
? failure.getCause() : failure;
|
||||
throw new IllegalStateException("核心 " + core + " 的原生调度 API 不完整,无法启用插件: " + cause, cause);
|
||||
}
|
||||
try {
|
||||
bukkit = server.getScheduler();
|
||||
if (bukkit == null || !server.isPrimaryThread()) {
|
||||
throw new IllegalStateException("缺少可用 BukkitScheduler 或启用过程未运行在主线程");
|
||||
}
|
||||
} catch (RuntimeException | LinkageError unavailable) {
|
||||
throw new IllegalStateException("核心 " + core + " 的 Bukkit 调度能力验证失败: "
|
||||
+ unavailable, unavailable);
|
||||
}
|
||||
adapter = Adapter.BUKKIT;
|
||||
}
|
||||
|
||||
String minecraftVersion = brand == null ? apiVersion.split("-", 2)[0] : brand.minecraftVersion();
|
||||
CoreInfo info = new CoreInfo(core, brand == null ? name : brand.id(), version, minecraftVersion,
|
||||
apiVersion, System.getProperty("java.version"), folia, paperApi, nativeApi != null, adapter.className);
|
||||
return new Detection(info, adapter, nativeApi, bukkit);
|
||||
}
|
||||
|
||||
static String identify(String brandId, String name, String version) {
|
||||
return identify(brandId == null ? null : new Brand(brandId, ""), name, version);
|
||||
}
|
||||
|
||||
private static String identify(Brand brand, String name, String version) {
|
||||
String id = brand == null ? "" : brand.id().toLowerCase(Locale.ROOT);
|
||||
String reported = name.toLowerCase(Locale.ROOT);
|
||||
String build = version.toLowerCase(Locale.ROOT);
|
||||
if (id.equals("papermc:folia") || reported.equals("folia") || build.contains("git-folia-")) return "Folia";
|
||||
if (id.endsWith(":leaves") || reported.equals("leaves") || build.contains("git-leaves-")) return "Leaves";
|
||||
if (id.endsWith(":purpur") || reported.equals("purpur") || build.contains("git-purpur-")) return "Purpur";
|
||||
if (id.equals("papermc:paper") || reported.equals("paper") || build.contains("git-paper-")) return "Paper";
|
||||
if (reported.equals("spigot") || build.contains("-spigot-")) return "Spigot";
|
||||
return "Unknown (" + name + ")";
|
||||
}
|
||||
|
||||
private static Brand readBrand() {
|
||||
try {
|
||||
Class<?> type = Class.forName("io.papermc.paper.ServerBuildInfo", false, Server.class.getClassLoader());
|
||||
Object info = type.getMethod("buildInfo").invoke(null);
|
||||
return new Brand(type.getMethod("brandId").invoke(info).toString(),
|
||||
(String) type.getMethod("minecraftVersionId").invoke(info));
|
||||
} catch (ReflectiveOperationException | LinkageError ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasClass(String name) {
|
||||
try {
|
||||
Class.forName(name, false, Server.class.getClassLoader());
|
||||
return true;
|
||||
} catch (ClassNotFoundException missing) {
|
||||
return false;
|
||||
} catch (LinkageError broken) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean hasNativeSchedulerMethods() {
|
||||
try {
|
||||
for (Method method : Server.class.getMethods()) {
|
||||
if (switch (method.getName()) {
|
||||
case "getGlobalRegionScheduler", "getRegionScheduler", "getAsyncScheduler" -> true;
|
||||
default -> false;
|
||||
}) return true;
|
||||
}
|
||||
return Entity.class.getMethod("getScheduler") != null;
|
||||
} catch (NoSuchMethodException missing) {
|
||||
return false;
|
||||
} catch (LinkageError broken) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package dev.itxiaohui.contentguard.core;
|
||||
|
||||
public record CoreInfo(
|
||||
String coreName, String brand, String coreVersion, String minecraftVersion,
|
||||
String apiVersion, String javaVersion, boolean folia, boolean paperApi,
|
||||
boolean nativeSchedulers, String adapter
|
||||
) {
|
||||
public String summary() {
|
||||
return "core=" + coreName + " brand=" + brand + " server=" + coreVersion
|
||||
+ " mc=" + minecraftVersion + " api=" + apiVersion + " java=" + javaVersion
|
||||
+ " folia=" + folia + " paperApi=" + paperApi + " nativeSchedulers=" + nativeSchedulers
|
||||
+ " adapter=" + adapter;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package dev.itxiaohui.contentguard.core;
|
||||
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
/** The native scheduler contract is shared by Paper and Folia. */
|
||||
final class FoliaSchedulerAdapter extends PaperSchedulerAdapter {
|
||||
FoliaSchedulerAdapter(Plugin plugin, NativeSchedulerApi api) {
|
||||
super(plugin, api);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package dev.itxiaohui.contentguard.core;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
/** Describes the API using reflection only, so probing it is safe on Spigot. */
|
||||
record NativeSchedulerApi(
|
||||
Object global, Object region, Object async, Method entityGetter,
|
||||
Method globalRun, Method regionRun, Method asyncRun, Method entityRun, Method taskCancel
|
||||
) {
|
||||
private static final String API = "io.papermc.paper.threadedregions.scheduler.";
|
||||
|
||||
static NativeSchedulerApi probe(Server server) throws ReflectiveOperationException {
|
||||
ClassLoader loader = Server.class.getClassLoader();
|
||||
Class<?> task = Class.forName(API + "ScheduledTask", false, loader);
|
||||
Method global = getter(Server.class, "getGlobalRegionScheduler", API + "GlobalRegionScheduler");
|
||||
Method region = getter(Server.class, "getRegionScheduler", API + "RegionScheduler");
|
||||
Method async = getter(Server.class, "getAsyncScheduler", API + "AsyncScheduler");
|
||||
Method entity = getter(Entity.class, "getScheduler", API + "EntityScheduler");
|
||||
return new NativeSchedulerApi(
|
||||
instance(global, server), instance(region, server), instance(async, server), entity,
|
||||
schedulingMethod(global, "run", task, Plugin.class, Consumer.class),
|
||||
schedulingMethod(region, "run", task, Plugin.class, World.class, int.class, int.class, Consumer.class),
|
||||
schedulingMethod(async, "runNow", task, Plugin.class, Consumer.class),
|
||||
schedulingMethod(entity, "run", task, Plugin.class, Consumer.class, Runnable.class),
|
||||
task.getMethod("cancel")
|
||||
);
|
||||
}
|
||||
|
||||
private static Method getter(Class<?> owner, String name, String returnType) throws NoSuchMethodException {
|
||||
Method method = owner.getMethod(name);
|
||||
if (!method.getReturnType().getName().equals(returnType)) {
|
||||
throw new NoSuchMethodException(owner.getName() + "." + name + " must return " + returnType);
|
||||
}
|
||||
return method;
|
||||
}
|
||||
|
||||
private static Method schedulingMethod(Method getter, String name, Class<?> type, Class<?>... parameters)
|
||||
throws NoSuchMethodException {
|
||||
Method method = getter.getReturnType().getMethod(name, parameters);
|
||||
if (method.getReturnType() != type) {
|
||||
throw new NoSuchMethodException(method + " must return " + type.getName());
|
||||
}
|
||||
return method;
|
||||
}
|
||||
|
||||
private static Object instance(Method method, Server server) throws ReflectiveOperationException {
|
||||
Object result = method.invoke(server);
|
||||
if (result == null) {
|
||||
throw new NoSuchMethodException(method + " returned null");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static Object invoke(Method method, Object receiver, Object... arguments) {
|
||||
try {
|
||||
return method.invoke(receiver, arguments);
|
||||
} catch (InvocationTargetException failure) {
|
||||
if (failure.getCause() instanceof RuntimeException runtime) {
|
||||
throw runtime;
|
||||
}
|
||||
if (failure.getCause() instanceof Error error) {
|
||||
throw error;
|
||||
}
|
||||
throw new IllegalStateException("Scheduler API failed: " + method.getName(), failure.getCause());
|
||||
} catch (IllegalAccessException failure) {
|
||||
throw new IllegalStateException("Scheduler API is inaccessible: " + method.getName(), failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package dev.itxiaohui.contentguard.core;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
class PaperSchedulerAdapter extends TrackedScheduler {
|
||||
private final Plugin plugin;
|
||||
private final NativeSchedulerApi api;
|
||||
|
||||
PaperSchedulerAdapter(Plugin plugin, NativeSchedulerApi api) {
|
||||
this.plugin = plugin;
|
||||
this.api = api;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Task global(Runnable action) {
|
||||
return submit(action, () -> {}, task -> {
|
||||
Consumer<Object> callback = ignored -> task.run();
|
||||
return cancellation(NativeSchedulerApi.invoke(api.globalRun(), api.global(), plugin, callback));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Task region(World world, int chunkX, int chunkZ, Runnable action) {
|
||||
Objects.requireNonNull(world, "world");
|
||||
return submit(action, () -> {}, task -> {
|
||||
Consumer<Object> callback = ignored -> task.run();
|
||||
return cancellation(NativeSchedulerApi.invoke(api.regionRun(), api.region(),
|
||||
plugin, world, chunkX, chunkZ, callback));
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Task entity(Entity entity, Runnable action, Runnable retired) {
|
||||
Objects.requireNonNull(entity, "entity");
|
||||
return submit(action, retired, task -> {
|
||||
Object owner = NativeSchedulerApi.invoke(api.entityGetter(), entity);
|
||||
Consumer<Object> callback = ignored -> task.run();
|
||||
Object handle = NativeSchedulerApi.invoke(api.entityRun(), owner, plugin, callback, (Runnable) task::retired);
|
||||
if (handle == null) {
|
||||
task.retired();
|
||||
return () -> {};
|
||||
}
|
||||
return cancellation(handle);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Task async(Runnable action) {
|
||||
return submit(action, () -> {}, task -> {
|
||||
Consumer<Object> callback = ignored -> task.run();
|
||||
return cancellation(NativeSchedulerApi.invoke(api.asyncRun(), api.async(), plugin, callback));
|
||||
});
|
||||
}
|
||||
|
||||
private Runnable cancellation(Object handle) {
|
||||
Objects.requireNonNull(handle, "Scheduler returned no task handle");
|
||||
return () -> NativeSchedulerApi.invoke(api.taskCancel(), handle);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package dev.itxiaohui.contentguard.core;
|
||||
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Entity;
|
||||
|
||||
public interface ServerScheduler extends AutoCloseable {
|
||||
@FunctionalInterface
|
||||
interface Task {
|
||||
/** Cancels a task that has not started. */
|
||||
boolean cancel();
|
||||
}
|
||||
|
||||
Task global(Runnable action);
|
||||
Task region(World world, int chunkX, int chunkZ, Runnable action);
|
||||
|
||||
/**
|
||||
* Submits work to the thread that owns this entity when the task runs.
|
||||
* The retirement callback must be thread-safe and must not access Bukkit state.
|
||||
* Explicit cancellation and adapter shutdown suppress the retirement callback.
|
||||
*/
|
||||
Task entity(Entity entity, Runnable action, Runnable retired);
|
||||
|
||||
/** Submits short asynchronous callbacks. Bulk I/O should use a bounded worker queue. */
|
||||
Task async(Runnable action);
|
||||
|
||||
@Override
|
||||
void close();
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package dev.itxiaohui.contentguard.core;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
|
||||
abstract class TrackedScheduler implements ServerScheduler {
|
||||
private static final int PENDING = 0;
|
||||
private static final int RUNNING = 1;
|
||||
private static final int TERMINAL = 2;
|
||||
|
||||
private final Set<PendingTask> pending = new HashSet<>();
|
||||
private boolean closed;
|
||||
|
||||
protected final Task submit(Runnable action, Runnable retired, Function<PendingTask, Runnable> schedule) {
|
||||
Objects.requireNonNull(action, "action");
|
||||
Objects.requireNonNull(retired, "retired");
|
||||
PendingTask task = new PendingTask(action, retired);
|
||||
synchronized (pending) {
|
||||
if (closed) {
|
||||
throw new RejectedExecutionException("Server scheduler has closed");
|
||||
}
|
||||
pending.add(task);
|
||||
}
|
||||
try {
|
||||
task.attach(schedule.apply(task));
|
||||
return task;
|
||||
} catch (RuntimeException | Error failure) {
|
||||
task.cancel();
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void close() {
|
||||
PendingTask[] tasks;
|
||||
synchronized (pending) {
|
||||
closed = true;
|
||||
tasks = pending.toArray(PendingTask[]::new);
|
||||
}
|
||||
for (PendingTask task : tasks) {
|
||||
task.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
protected final class PendingTask implements Task {
|
||||
private final Runnable action;
|
||||
private final Runnable retired;
|
||||
private final AtomicInteger state = new AtomicInteger(PENDING);
|
||||
private boolean cancelled;
|
||||
private Runnable cancellation;
|
||||
|
||||
private PendingTask(Runnable action, Runnable retired) {
|
||||
this.action = action;
|
||||
this.retired = retired;
|
||||
}
|
||||
|
||||
private void attach(Runnable cancellation) {
|
||||
boolean cancelNow;
|
||||
synchronized (this) {
|
||||
cancelNow = cancelled;
|
||||
if (!cancelNow && state.get() == PENDING) {
|
||||
this.cancellation = cancellation;
|
||||
}
|
||||
}
|
||||
if (cancelNow) {
|
||||
cancellation.run();
|
||||
}
|
||||
}
|
||||
|
||||
void run() {
|
||||
finish(action);
|
||||
}
|
||||
|
||||
void retired() {
|
||||
finish(retired);
|
||||
}
|
||||
|
||||
private void finish(Runnable callback) {
|
||||
synchronized (pending) {
|
||||
if (closed || !state.compareAndSet(PENDING, RUNNING)) {
|
||||
return;
|
||||
}
|
||||
pending.remove(this);
|
||||
}
|
||||
try {
|
||||
callback.run();
|
||||
} finally {
|
||||
synchronized (this) {
|
||||
state.set(TERMINAL);
|
||||
cancellation = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean cancel() {
|
||||
Runnable callback;
|
||||
synchronized (this) {
|
||||
if (!state.compareAndSet(PENDING, TERMINAL)) {
|
||||
return false;
|
||||
}
|
||||
cancelled = true;
|
||||
callback = cancellation;
|
||||
cancellation = null;
|
||||
}
|
||||
synchronized (pending) {
|
||||
pending.remove(this);
|
||||
}
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
name: ItxiaohuiContentGuard
|
||||
main: dev.itxiaohui.contentguard.ContentGuardPlugin
|
||||
version: '${version}'
|
||||
api-version: '1.21'
|
||||
folia-supported: true
|
||||
description: 小慧内容卫士核心适配
|
||||
commands:
|
||||
icg:
|
||||
description: 查看服务端核心与调度器
|
||||
usage: /icg info
|
||||
permission: itxiaohui.contentguard.admin
|
||||
permissions:
|
||||
itxiaohui.contentguard.admin:
|
||||
description: 管理小慧内容卫士
|
||||
default: op
|
||||
@@ -0,0 +1,64 @@
|
||||
package dev.itxiaohui.contentguard.core;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import org.bukkit.Server;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CoreDetectorTest {
|
||||
@ParameterizedTest
|
||||
@CsvSource(value = {
|
||||
"papermc:paper, Paper, 1.21.8, Paper",
|
||||
"purpurmc:purpur, Paper, 1.21.8, Purpur",
|
||||
"leavesmc:leaves, Paper, 1.21.8, Leaves",
|
||||
"papermc:folia, Paper, 1.21.8, Folia",
|
||||
"NULL, CraftBukkit, git-Spigot-123, Spigot",
|
||||
"NULL, CraftBukkit, 4534-Spigot-7c52c66-65f1f11 (MC: 1.21.8), Spigot",
|
||||
"NULL, Fork, 1.21.8, Unknown (Fork)"
|
||||
}, nullValues = "NULL")
|
||||
void identifiesBrand(String brand, String name, String version, String expected) {
|
||||
assertEquals(expected, CoreDetector.identify(brand, name, version));
|
||||
}
|
||||
|
||||
@Test
|
||||
void usesBukkitAfterCheckingUnknownCoreCapabilities() {
|
||||
CoreInfo info = new CoreDetector().detect(server("Independent", true));
|
||||
assertEquals("Unknown (Independent)", info.coreName());
|
||||
assertEquals("BukkitSchedulerAdapter", info.adapter());
|
||||
assertEquals("1.21.8", info.minecraftVersion());
|
||||
assertFalse(info.nativeSchedulers());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnknownCoreWithoutPrimaryThread() {
|
||||
var failure = assertThrows(IllegalStateException.class,
|
||||
() -> new CoreDetector().detect(server("Independent", false)));
|
||||
assertTrue(failure.getMessage().contains("Bukkit 调度能力验证失败"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesBukkitFallbackForIncompleteFolia() {
|
||||
var failure = assertThrows(IllegalStateException.class,
|
||||
() -> new CoreDetector().detect(server("Folia", true)));
|
||||
assertTrue(failure.getMessage().contains("原生调度 API 不完整"));
|
||||
}
|
||||
|
||||
private Server server(String name, boolean primaryThread) {
|
||||
ClassLoader loader = Server.class.getClassLoader();
|
||||
var scheduler = (BukkitScheduler) Proxy.newProxyInstance(loader,
|
||||
new Class<?>[]{BukkitScheduler.class}, (proxy, method, args) -> null);
|
||||
return (Server) Proxy.newProxyInstance(loader, new Class<?>[]{Server.class}, (proxy, method, args) ->
|
||||
switch (method.getName()) {
|
||||
case "getName" -> name;
|
||||
case "getVersion" -> "test-build";
|
||||
case "getBukkitVersion" -> "1.21.8-R0.1-SNAPSHOT";
|
||||
case "getScheduler" -> scheduler;
|
||||
case "isPrimaryThread" -> primaryThread;
|
||||
default -> throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package dev.itxiaohui.contentguard.core;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Entity;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class TrackedSchedulerTest {
|
||||
@Test
|
||||
void retirementAndRunAreMutuallyExclusive() {
|
||||
var scheduler = new TestScheduler();
|
||||
var actions = new AtomicInteger();
|
||||
var retirements = new AtomicInteger();
|
||||
var handle = scheduler.queue(actions::incrementAndGet, retirements::incrementAndGet, ignored -> () -> {});
|
||||
scheduler.task.retired();
|
||||
scheduler.task.run();
|
||||
assertFalse(handle.cancel());
|
||||
assertEquals(0, actions.get());
|
||||
assertEquals(1, retirements.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shutdownCancelsNativeHandleEvenIfItArrivesAfterShutdown() throws Exception {
|
||||
var scheduler = new TestScheduler();
|
||||
var entered = new CountDownLatch(1);
|
||||
var release = new CountDownLatch(1);
|
||||
var executions = new AtomicInteger();
|
||||
var cancellations = new AtomicInteger();
|
||||
try (var worker = Executors.newSingleThreadExecutor()) {
|
||||
var handle = worker.submit(() -> scheduler.queue(executions::incrementAndGet,
|
||||
executions::incrementAndGet, ignored -> {
|
||||
entered.countDown();
|
||||
try {
|
||||
if (!release.await(5, TimeUnit.SECONDS)) throw new AssertionError("Scheduling stalled");
|
||||
} catch (InterruptedException failure) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new AssertionError(failure);
|
||||
}
|
||||
return cancellations::incrementAndGet;
|
||||
}));
|
||||
try {
|
||||
assertTrue(entered.await(5, TimeUnit.SECONDS));
|
||||
scheduler.close();
|
||||
scheduler.task.retired();
|
||||
scheduler.task.run();
|
||||
} finally {
|
||||
release.countDown();
|
||||
}
|
||||
assertFalse(handle.get(5, TimeUnit.SECONDS).cancel());
|
||||
}
|
||||
assertEquals(1, cancellations.get());
|
||||
assertEquals(0, executions.get());
|
||||
assertThrows(RejectedExecutionException.class, () -> scheduler.global(() -> {}));
|
||||
}
|
||||
|
||||
private static final class TestScheduler extends TrackedScheduler {
|
||||
private PendingTask task;
|
||||
|
||||
private Task queue(Runnable action, Runnable retired, Function<PendingTask, Runnable> nativeSubmit) {
|
||||
return submit(action, retired, pending -> {
|
||||
task = pending;
|
||||
return nativeSubmit.apply(pending);
|
||||
});
|
||||
}
|
||||
|
||||
@Override public Task global(Runnable action) { return queue(action, () -> {}, ignored -> () -> {}); }
|
||||
@Override public Task async(Runnable action) { return global(action); }
|
||||
@Override public Task region(World world, int x, int z, Runnable action) { return global(action); }
|
||||
@Override public Task entity(Entity entity, Runnable action, Runnable retired) {
|
||||
return queue(action, retired, ignored -> () -> {});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user