Merge pull request '加入服务端核心识别与原生调度适配' (#1) from feature/core-compatibility into main
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
commit
a9d572fff0
28 files changed
+1440
-2
No files matched your search
@@ -0,0 +1,2 @@
|
||||
gradlew text eol=lf
|
||||
gradlew.bat text eol=crlf
|
||||
@@ -0,0 +1,5 @@
|
||||
/.gradle/
|
||||
/.toolchains/
|
||||
/.test-servers/
|
||||
/build/
|
||||
__pycache__/
|
||||
@@ -1,3 +1,30 @@
|
||||
# ItxiaohuiContentGuard
|
||||
# ItxiaohuiContentGuard · 小慧内容卫士
|
||||
|
||||
Minecraft Java 1.21.x 多核心智能内容审核插件,兼容 Paper、Purpur、Spigot、Folia、Leaves,支持本地敏感词过滤、AI 智能审核、SMTP 邮件告警及 SQLite 违规记录,自动识别服务端核心并适配调度器。
|
||||
面向 Minecraft Java 1.21.x 的服务端内容审核插件。当前阶段提供 Java 21 构建、核心识别、调度适配和实服兼容探针。聊天、书本、AI、SMTP 和 SQLite 审核将在后续阶段提交。
|
||||
|
||||
## 兼容适配
|
||||
|
||||
- 启动时核对服务端品牌、构建版本和调度 API 能力。`/icg info` 输出检测结果和已选适配器。
|
||||
- Spigot 使用 Bukkit 调度器。Paper、Purpur、Leaves 在原生接口完整时使用 Paper 调度器。
|
||||
- Folia 将全局、区块、实体和异步任务提交到对应的原生调度器。实体任务处理失效、取消和停用。
|
||||
- 未知核心按 API 能力检测。识别到原生调度能力却缺少完整接口时会记录失败并停用插件。
|
||||
|
||||
## 构建
|
||||
|
||||
需要 Java 21。Windows 使用以下命令,其他系统使用 `./gradlew`。
|
||||
|
||||
```powershell
|
||||
.\gradlew.bat build compatProbeJar
|
||||
```
|
||||
|
||||
## 复现实服探针
|
||||
|
||||
1. 使用 `python scripts/fetch-servers.py --download --version 1.21.8` 获取 Paper、Purpur、Folia 和 Leaves。使用 `python scripts/build-spigot.py --java <java路径> --version 1.21.8` 编译 Spigot。
|
||||
2. 每个核心采用独立的工作目录、服务端、配置、世界与日志。测试服监听回环地址。
|
||||
3. 将 `build/libs/ItxiaohuiContentGuard-0.1.0-dev.jar` 和 `build/libs/ItxiaohuiContentGuard-0.1.0-dev-compat-probe.jar` 装到测试实例的 `plugins` 目录。
|
||||
4. 启动后从控制台运行 `icg info` 和 `icgprobe`。通过客户端登录以触发实体调度与取消。Folia 探针同时检查全局线程与区块权属。
|
||||
5. 正常关服并在同一实例目录重启。核对 `ICG_LIFECYCLE scheduler=closed`、核心信息和 `ICG_PROBE` 各项结果。
|
||||
|
||||
协议客户端测试可使用 Node.js 和固定版本 `minecraft-protocol@1.68.0`。运行 `node scripts/compat-client.cjs <minecraft-protocol 的绝对模块路径> <端口> 1.21.8`。
|
||||
|
||||
每个核心和小版本都需要完整功能、压力、故障与稳定性证据后才会标记为正式兼容。
|
||||
@@ -0,0 +1,54 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
}
|
||||
|
||||
group = 'dev.itxiaohui.contentguard'
|
||||
version = '0.1.0-dev'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven {
|
||||
url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/')
|
||||
content { includeGroup('org.spigotmc') }
|
||||
}
|
||||
}
|
||||
|
||||
java {
|
||||
toolchain { languageVersion = JavaLanguageVersion.of(21) }
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly 'org.spigotmc:spigot-api:1.21.1-R0.1-SNAPSHOT'
|
||||
testImplementation 'org.spigotmc:spigot-api:1.21.1-R0.1-SNAPSHOT'
|
||||
testImplementation platform('org.junit:junit-bom:5.13.4')
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
}
|
||||
|
||||
tasks.withType(JavaCompile).configureEach {
|
||||
options.encoding = 'UTF-8'
|
||||
options.release = 21
|
||||
}
|
||||
|
||||
processResources {
|
||||
inputs.property('version', project.version)
|
||||
filesMatching('plugin.yml') { expand(version: project.version) }
|
||||
}
|
||||
|
||||
test { useJUnitPlatform() }
|
||||
|
||||
sourceSets {
|
||||
compatProbe {
|
||||
compileClasspath += sourceSets.main.output + configurations.compileClasspath
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register('compatProbeJar', Jar) {
|
||||
archiveClassifier = 'compat-probe'
|
||||
from sourceSets.compatProbe.output
|
||||
}
|
||||
|
||||
tasks.withType(AbstractArchiveTask).configureEach {
|
||||
preserveFileTimestamps = false
|
||||
reproducibleFileOrder = true
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
# 1.21.8 核心适配探针
|
||||
|
||||
环境为 Windows 11 x64 和 Microsoft OpenJDK 21.0.13.0.2。
|
||||
开始 2026-11-15T10:29:13+08:00,结束 2026-11-15T10:30:10+08:00。
|
||||
|
||||
测试插件 JAR SHA-256 为 `a100eeef27711c6740ac3ddfdb75e58158c6312a43418d58984e454f78ab76d7`。
|
||||
|
||||
| 核心 | 实际版本 | 适配器 | 适配用例 | 正式状态 |
|
||||
|---|---|---|---:|---|
|
||||
| Paper | `1.21.8-60-29c8822 (MC: 1.21.8)` | `PaperSchedulerAdapter` | 11 / 11 | UNVERIFIED |
|
||||
| Purpur | `1.21.8-2497-a49cdb9 (MC: 1.21.8)` | `PaperSchedulerAdapter` | 11 / 11 | UNVERIFIED |
|
||||
| Spigot | `4534-Spigot-7c52c66-65f1f11 (MC: 1.21.8)` | `BukkitSchedulerAdapter` | 11 / 11 | UNVERIFIED |
|
||||
| Folia | `1.21.8-6-612d9bd (MC: 1.21.8)` | `FoliaSchedulerAdapter` | 11 / 11 | UNVERIFIED |
|
||||
| Leaves | `1.21.8-138-9331167 (MC: 1.21.8)` | `PaperSchedulerAdapter` | 11 / 11 | UNVERIFIED |
|
||||
|
||||
每个核心使用独立服务端、世界、配置和日志。实服探针覆盖启动、核心识别、全局、区块、异步、在线玩家实体任务、取消与原目录重启。
|
||||
JUnit 5 共 12 例通过,覆盖品牌差异、未知或不完整 API、退役与关闭竞争。
|
||||
完整内容审核、压力、故障和长时间稳定性属于后续验收。
|
||||
Vendored
BIN
Binary file not shown.
+8
@@ -0,0 +1,8 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -0,0 +1,251 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+94
@@ -0,0 +1,94 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Build a genuine Spigot test server using official BuildTools."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TOOL_URL = "https://hub.spigotmc.org/jenkins/job/BuildTools/lastSuccessfulBuild/artifact/target/BuildTools.jar"
|
||||
|
||||
|
||||
def sha256(path):
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--java", type=lambda value: Path(value).resolve(), required=True)
|
||||
parser.add_argument("--version", choices=("1.21.1", "1.21.4", "1.21.8", "1.21.11"), required=True)
|
||||
args = parser.parse_args()
|
||||
directory = ROOT / ".test-servers" / "spigot" / args.version
|
||||
build = directory / "buildtools"
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
jar = build / "BuildTools.jar"
|
||||
if not jar.is_file():
|
||||
partial = build / "BuildTools.download"
|
||||
subprocess.run(["curl", "-fsSL", "--retry", "2", "--connect-timeout", "10",
|
||||
"--max-time", "120", TOOL_URL, "-o", str(partial)], check=True)
|
||||
partial.replace(jar)
|
||||
log = build / "build.log"
|
||||
with log.open("wb") as output:
|
||||
subprocess.run([str(args.java), "-Dfile.encoding=UTF-8", "-Xmx3G", "-jar", str(jar),
|
||||
"--rev", args.version, "--compile", "SPIGOT", "--nogui"],
|
||||
cwd=build, stdout=output, stderr=subprocess.STDOUT, check=True)
|
||||
final = directory / "server.jar"
|
||||
shutil.copy2(build / f"spigot-{args.version}.jar", final)
|
||||
data = {"core": "spigot", "version": args.version, "buildtools_url": TOOL_URL,
|
||||
"buildtools_sha256": sha256(jar), "server_sha256": sha256(final),
|
||||
"build_log": str(log)}
|
||||
(directory / "source.json").write_text(json.dumps(data, indent=2), encoding="utf-8")
|
||||
print(final)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,33 @@
|
||||
const { createClient } = require(process.argv[2]);
|
||||
const client = createClient({
|
||||
host: "127.0.0.1",
|
||||
port: Number(process.argv[3]),
|
||||
version: process.argv[4],
|
||||
username: "ICGProbe",
|
||||
auth: "offline",
|
||||
hideErrors: true,
|
||||
});
|
||||
|
||||
let loggedIn = false;
|
||||
const timeout = setTimeout(() => {
|
||||
console.error("Timed out connecting to the test server");
|
||||
process.exit(1);
|
||||
}, 20_000);
|
||||
|
||||
client.on("login", () => {
|
||||
loggedIn = true;
|
||||
console.log("Minecraft protocol login completed");
|
||||
clearTimeout(timeout);
|
||||
setTimeout(() => client.end("Probe finished"), 4_000);
|
||||
});
|
||||
client.on("error", error => {
|
||||
console.error(error.message);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
client.on("end", reason => {
|
||||
clearTimeout(timeout);
|
||||
if (!loggedIn) {
|
||||
console.error("Disconnected before login:", reason);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Download pinned-by-evidence upstream builds for isolated compatibility runs."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
AGENT = os.environ.get("ICG_DOWNLOAD_USER_AGENT", "ItxiaohuiContentGuard-tests/0.1 (https://www.minecraft.net/)")
|
||||
VERSIONS = ("1.21.1", "1.21.4", "1.21.8", "1.21.11")
|
||||
CURL = "curl.exe" if os.name == "nt" else "curl"
|
||||
|
||||
|
||||
def fetch(url, destination=None, accept=None):
|
||||
command = [CURL, "-fsSL", "--retry", "2",
|
||||
"--connect-timeout", "8", "--max-time", "150", "-A", AGENT, url]
|
||||
if accept:
|
||||
command.extend(["-H", f"Accept: {accept}"])
|
||||
if destination:
|
||||
subprocess.run(command + ["-o", str(destination)], check=True, capture_output=True)
|
||||
else:
|
||||
return json.loads(subprocess.check_output(command, stderr=subprocess.PIPE))
|
||||
|
||||
|
||||
def leaves_release_asset(url, version):
|
||||
headers = subprocess.check_output(
|
||||
[CURL, "-fsS", "--connect-timeout", "8", "--max-time", "15", "-A", AGENT,
|
||||
"-D", "-", "-o", os.devnull, url], stderr=subprocess.PIPE, text=True)
|
||||
redirect = next(line.split(":", 1)[1].strip() for line in headers.splitlines()
|
||||
if line.lower().startswith("location:"))
|
||||
release = urlsplit(redirect)
|
||||
parts = release.path.split("/")
|
||||
if release.hostname != "github.com" or "/".join(parts[1:5]).lower() != "leavesmc/leaves/releases/download":
|
||||
raise ValueError("Leaves download did not redirect to its upstream GitHub releases")
|
||||
info = fetch(f"https://api.github.com/repos/LeavesMC/Leaves/releases/tags/{parts[5]}")
|
||||
return next(item for item in info["assets"] if item["name"] == f"leaves-{version}.jar")
|
||||
|
||||
|
||||
def build_info(core, version, allow_prerelease):
|
||||
if core in ("paper", "folia"):
|
||||
api = f"https://fill.papermc.io/v3/projects/{core}/versions/{version}/builds"
|
||||
builds = fetch(api)
|
||||
stable = [entry for entry in builds if entry["channel"] == "STABLE"]
|
||||
eligible = stable or (builds if allow_prerelease else [])
|
||||
if not eligible:
|
||||
raise ValueError("No stable build in upstream channel")
|
||||
build = max(eligible, key=lambda entry: entry["id"])
|
||||
asset = build["downloads"]["server:default"]
|
||||
return build["id"], build["channel"], asset["url"], asset["checksums"]["sha256"]
|
||||
if core == "purpur":
|
||||
api = f"https://api.purpurmc.org/v2/purpur/{version}"
|
||||
build = fetch(api)["builds"]["latest"]
|
||||
details = fetch(f"{api}/{build}")
|
||||
return build, details.get("result", "unknown"), f"{api}/{build}/download", None
|
||||
api = f"https://api.leavesmc.org/v2/projects/leaves/versions/{version}/builds"
|
||||
builds = fetch(api)["builds"]
|
||||
stable = [entry for entry in builds if entry["channel"] == "default"]
|
||||
eligible = stable or (builds if allow_prerelease else [])
|
||||
if not eligible:
|
||||
raise ValueError("No default-channel build in upstream channel")
|
||||
build = max(eligible, key=lambda entry: entry["build"])
|
||||
asset = build["downloads"]["application"]
|
||||
return (build["build"], build["channel"], f'{api}/{build["build"]}/downloads/{asset["name"]}', asset["sha256"])
|
||||
|
||||
|
||||
def acquire(core, version, should_download, allow_prerelease):
|
||||
destination = ROOT / ".test-servers" / core / version
|
||||
try:
|
||||
build, channel, url, checksum = build_info(core, version, allow_prerelease)
|
||||
status = {"core": core, "version": version, "build": build, "channel": channel,
|
||||
"url": url, "upstream_sha256": checksum}
|
||||
if should_download:
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
partial = destination / "server.download"
|
||||
try:
|
||||
fetch(url, partial)
|
||||
except subprocess.CalledProcessError:
|
||||
if core != "leaves":
|
||||
raise
|
||||
asset = leaves_release_asset(url, version)
|
||||
fetch(asset["url"] + "?download=1", partial, "application/octet-stream")
|
||||
status["url"] = asset["browser_download_url"]
|
||||
with partial.open("rb") as stream:
|
||||
actual = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if checksum and actual != checksum:
|
||||
raise ValueError(f"SHA-256 mismatch: {actual}")
|
||||
partial.replace(destination / "server.jar")
|
||||
status["sha256"] = actual
|
||||
(destination / "source.json").write_text(json.dumps(status, indent=2), encoding="utf-8")
|
||||
return status
|
||||
except subprocess.CalledProcessError as error:
|
||||
message = error.stderr if isinstance(error.stderr, str) else error.stderr.decode()
|
||||
return {"core": core, "version": version, "error": message.strip()}
|
||||
except (OSError, KeyError, IndexError, ValueError, StopIteration) as error:
|
||||
return {"core": core, "version": version, "error": str(error)}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--core", nargs="+", default=["paper", "purpur", "folia", "leaves"],
|
||||
choices=["paper", "purpur", "folia", "leaves"])
|
||||
parser.add_argument("--version", nargs="+", default=VERSIONS, choices=VERSIONS)
|
||||
parser.add_argument("--download", action="store_true")
|
||||
parser.add_argument("--allow-prerelease", action="store_true")
|
||||
args = parser.parse_args()
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = [pool.submit(acquire, core, version, args.download, args.allow_prerelease)
|
||||
for core in args.core for version in args.version]
|
||||
print(json.dumps([result.result() for result in results], ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = 'ItxiaohuiContentGuard'
|
||||
@@ -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