Simplify pack validation and merge response mixins
This commit is contained in:
@@ -1,23 +0,0 @@
|
||||
# AstraPacks — серверный мод NeoForge
|
||||
|
||||
Этот проект перенесён с Paper на NeoForge по прямому указанию пользователя.
|
||||
Правила ниже заменяют устаревшие указания о Paper-сервере из родительского AGENTS.md для AstraPacks.
|
||||
|
||||
- Исходники: `C:\Users\ScarPC\Documents\Plugins\AstraPacks`.
|
||||
- Рабочий сервер: `C:\Users\ScarPC\Documents\NeoForge Server 26.2`.
|
||||
- Платформа: Minecraft 26.2, NeoForge 26.2.0.79, Java 25+.
|
||||
- Мод только серверный. Клиент не обязан устанавливать NeoForge или AstraPacks.
|
||||
- Не добавлять зависимости на Bukkit, Paper, ItemsAdder или обязательные клиентские каналы.
|
||||
- После изменений кода/ресурсов выполнить сборку и соответствующие проверки.
|
||||
- Установить только успешно собранный JAR непосредственно в `mods` рабочего NeoForge-сервера.
|
||||
- Старый JAR именно AstraPacks, если он есть, перенести в `old-mods/YYYYMMDD-HHMMSS/`,
|
||||
не перезаписывая архивы. После копирования сверить SHA-256 установленного и собранного JAR.
|
||||
- Не использовать отложенную установку; не оставлять несколько версий в mods.
|
||||
- Не заменять конфигурацию, миры или пользовательские ресурсы при обновлении JAR.
|
||||
- Paper-сервер и его плагины при работе над этим модом не изменять.
|
||||
- Изменения завершённой задачи обязательно зафиксировать отдельным Git-коммитом;
|
||||
перед коммитом проверить diff. Не включать посторонние изменения пользователя.
|
||||
- JAR сборки, build, .gradle, журналы, тестовые серверы и резервные копии не коммитить.
|
||||
Стандартный `gradle/wrapper/gradle-wrapper.jar` является частью исходников сборочной системы.
|
||||
- Push только по запросу пользователя.
|
||||
- В итоге сообщить результат установки, путь архива прежнего JAR (если был) и коммит.
|
||||
+1
-1
@@ -3,7 +3,7 @@ plugins {
|
||||
id("net.neoforged.moddev") version "2.0.146"
|
||||
}
|
||||
group = "online.astradev"
|
||||
version = "0.2.1"
|
||||
version = "0.2.2"
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collection;
|
||||
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.arguments.EntityArgument;
|
||||
@@ -24,9 +21,14 @@ import net.neoforged.neoforge.event.server.ServerAboutToStartEvent;
|
||||
import net.neoforged.neoforge.event.server.ServerStoppedEvent;
|
||||
import net.neoforged.neoforge.event.tick.ServerTickEvent;
|
||||
import net.neoforged.neoforge.network.event.RegisterConfigurationTasksEvent;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collection;
|
||||
|
||||
@Mod(value = "astrapacks", dist = Dist.DEDICATED_SERVER)
|
||||
public final class AstraPacks {
|
||||
public static final Logger LOG = LoggerFactory.getLogger("AstraPacks");
|
||||
@@ -103,15 +105,19 @@ public final class AstraPacks {
|
||||
}
|
||||
|
||||
private void registerCommands(RegisterCommandsEvent event) {
|
||||
LiteralArgumentBuilder<CommandSourceStack> command = Commands.literal("astrapacks")
|
||||
.requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
||||
.executes(this::status);
|
||||
LiteralArgumentBuilder<CommandSourceStack> command =
|
||||
Commands.literal("astrapacks")
|
||||
.requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
||||
.executes(this::status);
|
||||
|
||||
command.then(Commands.literal("status").executes(this::status));
|
||||
command.then(Commands.literal("build").executes(this::build));
|
||||
command.then(Commands.literal("reload").executes(this::reload));
|
||||
command.then(Commands.literal("send")
|
||||
.then(Commands.argument("players", EntityArgument.players()).executes(this::send)));
|
||||
command.then(
|
||||
Commands.literal("send")
|
||||
.then(
|
||||
Commands.argument("players", EntityArgument.players())
|
||||
.executes(this::send)));
|
||||
|
||||
event.getDispatcher().register(command);
|
||||
}
|
||||
@@ -144,7 +150,8 @@ public final class AstraPacks {
|
||||
for (ServerPlayer player : players) {
|
||||
runtime.session(player.connection).start(player.connection::send);
|
||||
}
|
||||
source.sendSuccess(() -> Component.literal("Ресурспак отправлен: " + players.size()), false);
|
||||
source.sendSuccess(
|
||||
() -> Component.literal("Ресурспак отправлен: " + players.size()), false);
|
||||
return players.size();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
@@ -16,9 +19,6 @@ import java.util.HexFormat;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
/** Archives the shared content directory, keeping the current and one previous ZIP. */
|
||||
public final class PackBuilder {
|
||||
public record Pack(Path path, String sha1, int files, long bytes) {}
|
||||
@@ -71,19 +71,29 @@ public final class PackBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
private int writeArchive(Path contents, Path target, String resourceVersion) throws IOException {
|
||||
// Shared with server-side exporters (AstraPlus). A build must see one complete asset generation.
|
||||
String lock = "AstraPacks:contents:" + contents.toAbsolutePath().normalize().toString().toLowerCase(java.util.Locale.ROOT);
|
||||
private int writeArchive(Path contents, Path target, String resourceVersion)
|
||||
throws IOException {
|
||||
// Shared with server-side exporters (AstraPlus). A build must see one complete asset
|
||||
// generation.
|
||||
String lock =
|
||||
"AstraPacks:contents:"
|
||||
+ contents.toAbsolutePath()
|
||||
.normalize()
|
||||
.toString()
|
||||
.toLowerCase(java.util.Locale.ROOT);
|
||||
synchronized (lock.intern()) {
|
||||
return writeLockedArchive(contents, target, resourceVersion);
|
||||
}
|
||||
}
|
||||
|
||||
private int writeLockedArchive(Path contents, Path target, String resourceVersion) throws IOException {
|
||||
private int writeLockedArchive(Path contents, Path target, String resourceVersion)
|
||||
throws IOException {
|
||||
int files = 0;
|
||||
long totalBytes = 0;
|
||||
try (var paths = Files.walk(contents);
|
||||
var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(target)))) {
|
||||
var zip =
|
||||
new ZipOutputStream(
|
||||
new BufferedOutputStream(Files.newOutputStream(target)))) {
|
||||
for (Path file : paths.sorted().toList()) {
|
||||
if (Files.isSymbolicLink(file)) {
|
||||
throw new IOException("Symbolic links are not supported: " + file);
|
||||
@@ -105,8 +115,10 @@ public final class PackBuilder {
|
||||
ZipEntry entry = new ZipEntry(name);
|
||||
entry.setTime(0);
|
||||
zip.putNextEntry(entry);
|
||||
long limit = Math.min(config.build.maxFileMiB * 1024L * 1024L,
|
||||
config.build.maxTotalMiB * 1024L * 1024L - totalBytes);
|
||||
long limit =
|
||||
Math.min(
|
||||
config.build.maxFileMiB * 1024L * 1024L,
|
||||
config.build.maxTotalMiB * 1024L * 1024L - totalBytes);
|
||||
totalBytes += copyResource(file, zip, limit);
|
||||
zip.closeEntry();
|
||||
}
|
||||
@@ -119,7 +131,8 @@ public final class PackBuilder {
|
||||
return files + 1;
|
||||
}
|
||||
|
||||
private static long copyResource(Path file, OutputStream output, long limit) throws IOException {
|
||||
private static long copyResource(Path file, OutputStream output, long limit)
|
||||
throws IOException {
|
||||
byte[] buffer = new byte[8192];
|
||||
long size = 0;
|
||||
try (var input = Files.newInputStream(file)) {
|
||||
@@ -168,14 +181,14 @@ public final class PackBuilder {
|
||||
try (var paths = Files.list(output)) {
|
||||
for (Path path : paths.toList()) {
|
||||
String name = path.getFileName().toString();
|
||||
if (name.matches("[a-f0-9]{40}\\.zip") && !name.equals(pack.sha1() + ".zip")
|
||||
&& (previous == null || !name.equals(previous + ".zip"))
|
||||
&& Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {
|
||||
Files.delete(path);
|
||||
}
|
||||
if (!name.matches("[a-f0-9]{40}\\.zip")) continue;
|
||||
if (name.equals(pack.sha1() + ".zip")) continue;
|
||||
if (previous != null && name.equals(previous + ".zip")) continue;
|
||||
if (Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) Files.delete(path);
|
||||
}
|
||||
}
|
||||
PackFiles.atomicWrite(manifest, PackConfig.JSON.toJson(info).getBytes(StandardCharsets.UTF_8));
|
||||
PackFiles.atomicWrite(
|
||||
manifest, PackConfig.JSON.toJson(info).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static Pack latest(Path root, PackConfig config) throws IOException {
|
||||
@@ -192,11 +205,16 @@ public final class PackBuilder {
|
||||
private static JsonObject readManifest(Path path) throws IOException {
|
||||
try {
|
||||
JsonObject info = JsonParser.parseString(Files.readString(path)).getAsJsonObject();
|
||||
if (!info.get("sha1").getAsString().matches("[a-f0-9]{40}")
|
||||
|| (info.has("previousSha1") && !info.get("previousSha1").getAsString().matches("[a-f0-9]{40}"))
|
||||
|| info.get("files").getAsInt() < 1) {
|
||||
throw new IOException("Invalid resource pack manifest: " + path);
|
||||
String current = info.get("sha1").getAsString();
|
||||
if (!current.matches("[a-f0-9]{40}"))
|
||||
throw new IOException("Invalid current pack hash: " + path);
|
||||
if (info.has("previousSha1")) {
|
||||
String previous = info.get("previousSha1").getAsString();
|
||||
if (!previous.matches("[a-f0-9]{40}"))
|
||||
throw new IOException("Invalid previous pack hash: " + path);
|
||||
}
|
||||
if (info.get("files").getAsInt() < 1)
|
||||
throw new IOException("Empty resource pack manifest: " + path);
|
||||
return info;
|
||||
} catch (RuntimeException e) {
|
||||
throw new IOException("Invalid resource pack manifest: " + path, e);
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -8,12 +11,10 @@ import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
/** Server-local configuration, deliberately never synchronized to clients. */
|
||||
public final class PackConfig {
|
||||
public static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||
public static final Gson JSON =
|
||||
new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||
|
||||
public boolean enabled = true;
|
||||
public Build build = new Build();
|
||||
@@ -62,13 +63,18 @@ public final class PackConfig {
|
||||
}
|
||||
|
||||
public static final class Messages {
|
||||
public String prompt = "&6Привет, {player}!\\n"
|
||||
+ "&fДля игры на сервере необходим ресурспак AstraDev.\\n"
|
||||
+ "&aНажми «Продолжить», чтобы загрузить его.";
|
||||
public String declined = "&cДля входа необходимо принять ресурспак сервера.\\n"
|
||||
+ "&fВ настройках этого сервера включи «Наборы ресурсов сервера» и подключись снова.";
|
||||
public String failed = "&cНе удалось загрузить ресурспак сервера.\\n"
|
||||
+ "&fПопробуй подключиться ещё раз. Если ошибка повторится, сообщи администрации.";
|
||||
public String prompt =
|
||||
"&6Привет, {player}!\\n"
|
||||
+ "&fДля игры на сервере необходим ресурспак AstraDev.\\n"
|
||||
+ "&aНажми «Продолжить», чтобы загрузить его.";
|
||||
public String declined =
|
||||
"&cДля входа необходимо принять ресурспак сервера.\\n"
|
||||
+ "&fВ настройках этого сервера включи «Наборы ресурсов сервера» и подключись"
|
||||
+ " снова.";
|
||||
public String failed =
|
||||
"&cНе удалось загрузить ресурспак сервера.\\n"
|
||||
+ "&fПопробуй подключиться ещё раз. Если ошибка повторится, сообщи"
|
||||
+ " администрации.";
|
||||
public String timeout = "&cВремя ожидания ресурспака истекло. Попробуй подключиться снова.";
|
||||
public String unavailable = "&cРесурспак сервера пока недоступен. Попробуй зайти позже.";
|
||||
public String loaded = "&aРесурспак AstraDev загружен.";
|
||||
@@ -76,7 +82,8 @@ public final class PackConfig {
|
||||
|
||||
public static PackConfig load(Path path) throws IOException {
|
||||
if (!Files.exists(path)) {
|
||||
byte[] defaults = (JSON.toJson(new PackConfig()) + "\n").getBytes(StandardCharsets.UTF_8);
|
||||
byte[] defaults =
|
||||
(JSON.toJson(new PackConfig()) + "\n").getBytes(StandardCharsets.UTF_8);
|
||||
PackFiles.atomicWrite(path, defaults);
|
||||
}
|
||||
try {
|
||||
@@ -112,8 +119,14 @@ public final class PackConfig {
|
||||
throw new IllegalArgumentException("tokenLifetimeSeconds must be >= timeoutSeconds");
|
||||
}
|
||||
|
||||
var texts = List.of(messages.prompt, messages.declined, messages.failed,
|
||||
messages.timeout, messages.unavailable, messages.loaded);
|
||||
var texts =
|
||||
List.of(
|
||||
messages.prompt,
|
||||
messages.declined,
|
||||
messages.failed,
|
||||
messages.timeout,
|
||||
messages.unavailable,
|
||||
messages.loaded);
|
||||
for (String message : texts) {
|
||||
if (message.length() > 8192) {
|
||||
throw new IllegalArgumentException("Message exceeds 8192 characters");
|
||||
@@ -135,8 +148,10 @@ public final class PackConfig {
|
||||
private void validateHosting() {
|
||||
Objects.requireNonNull(hosting.bindAddress, "hosting.bindAddress");
|
||||
Objects.requireNonNull(hosting.publicAddress, "hosting.publicAddress");
|
||||
if (!hosting.publicAddress.isBlank() && validateUrl(hosting.publicAddress).getQuery() != null) {
|
||||
throw new IllegalArgumentException("hosting.publicAddress must not contain query parameters");
|
||||
if (!hosting.publicAddress.isBlank()
|
||||
&& validateUrl(hosting.publicAddress).getQuery() != null) {
|
||||
throw new IllegalArgumentException(
|
||||
"hosting.publicAddress must not contain query parameters");
|
||||
}
|
||||
range(hosting.port, 1, 65535, "port");
|
||||
range(hosting.maxDownloadsPerIp, 1, 100, "maxDownloadsPerIp");
|
||||
@@ -148,7 +163,10 @@ public final class PackConfig {
|
||||
public static URI validateUrl(String value) {
|
||||
URI uri = URI.create(value);
|
||||
boolean http = "http".equals(uri.getScheme()) || "https".equals(uri.getScheme());
|
||||
if (!http || uri.getHost() == null || uri.getUserInfo() != null || uri.getFragment() != null) {
|
||||
if (!http
|
||||
|| uri.getHost() == null
|
||||
|| uri.getUserInfo() != null
|
||||
|| uri.getFragment() != null) {
|
||||
throw new IllegalArgumentException("Expected a direct http(s) URL: " + value);
|
||||
}
|
||||
return uri;
|
||||
|
||||
@@ -15,7 +15,11 @@ final class PackFiles {
|
||||
try {
|
||||
Files.write(temporary, bytes);
|
||||
try {
|
||||
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
|
||||
Files.move(
|
||||
temporary,
|
||||
target,
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException e) {
|
||||
Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
@@ -15,9 +18,6 @@ import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
/** Serves only published archives, with expiring links and bounded downloads. */
|
||||
public final class PackHost implements AutoCloseable {
|
||||
private record Grant(String hash, long expires) {}
|
||||
@@ -112,9 +112,12 @@ public final class PackHost implements AutoCloseable {
|
||||
for (String parameter : query.split("&")) {
|
||||
if (parameter.startsWith("token=")) {
|
||||
try {
|
||||
String token = URLDecoder.decode(parameter.substring(6), StandardCharsets.UTF_8);
|
||||
String token =
|
||||
URLDecoder.decode(parameter.substring(6), StandardCharsets.UTF_8);
|
||||
Grant grant = grants.get(token);
|
||||
return grant != null && grant.hash().equals(hash) && grant.expires() >= System.currentTimeMillis();
|
||||
return grant != null
|
||||
&& grant.hash().equals(hash)
|
||||
&& grant.expires() >= System.currentTimeMillis();
|
||||
} catch (IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
@@ -123,7 +126,8 @@ public final class PackHost implements AutoCloseable {
|
||||
return false;
|
||||
}
|
||||
|
||||
private void sendFile(HttpExchange exchange, Path file, String hash) throws IOException, InterruptedException {
|
||||
private void sendFile(HttpExchange exchange, Path file, String hash)
|
||||
throws IOException, InterruptedException {
|
||||
var headers = exchange.getResponseHeaders();
|
||||
headers.set("Content-Type", "application/zip");
|
||||
headers.set("ETag", '"' + hash + '"');
|
||||
@@ -144,7 +148,9 @@ public final class PackHost implements AutoCloseable {
|
||||
int read;
|
||||
while ((read = input.read(buffer)) != -1) {
|
||||
transferred += read;
|
||||
long delay = transferred * 1_000_000_000L / bytesPerSecond - (System.nanoTime() - started);
|
||||
long delay =
|
||||
transferred * 1_000_000_000L / bytesPerSecond
|
||||
- (System.nanoTime() - started);
|
||||
if (delay > 0) {
|
||||
TimeUnit.NANOSECONDS.sleep(delay);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,5 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.network.Connection;
|
||||
import net.minecraft.network.chat.Component;
|
||||
@@ -18,6 +9,15 @@ import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||
import net.minecraft.server.network.ServerGamePacketListenerImpl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
public final class PackRuntime implements AutoCloseable {
|
||||
public static volatile PackRuntime INSTANCE;
|
||||
|
||||
@@ -27,10 +27,12 @@ public final class PackRuntime implements AutoCloseable {
|
||||
private final Path root;
|
||||
private final Path configPath;
|
||||
private final PackHost host;
|
||||
private final Map<ServerCommonPacketListenerImpl, PackSession> sessions = new ConcurrentHashMap<>();
|
||||
private final Map<ServerCommonPacketListenerImpl, PackSession> sessions =
|
||||
new ConcurrentHashMap<>();
|
||||
private final Map<UUID, String> pendingWelcome = new ConcurrentHashMap<>();
|
||||
private final ExecutorService worker = Executors.newSingleThreadExecutor(
|
||||
Thread.ofPlatform().daemon().name("AstraPacks-build").factory());
|
||||
private final ExecutorService worker =
|
||||
Executors.newSingleThreadExecutor(
|
||||
Thread.ofPlatform().daemon().name("AstraPacks-build").factory());
|
||||
|
||||
private volatile PackConfig config;
|
||||
private volatile PackBuilder.Pack current;
|
||||
@@ -51,7 +53,9 @@ public final class PackRuntime implements AutoCloseable {
|
||||
return;
|
||||
}
|
||||
if (server.getServerResourcePack().isPresent()) {
|
||||
throw new IOException("AstraPacks must be the only pack sender: clear resource-pack in server.properties");
|
||||
throw new IOException(
|
||||
"AstraPacks must be the only pack sender: clear resource-pack in"
|
||||
+ " server.properties");
|
||||
}
|
||||
|
||||
Files.createDirectories(config.contents(root));
|
||||
@@ -62,10 +66,16 @@ public final class PackRuntime implements AutoCloseable {
|
||||
}
|
||||
host.start();
|
||||
if (config.hosting.publicAddress.isBlank()) {
|
||||
AstraPacks.LOG.error("Set hosting.publicAddress to the public HTTP address (port {}). Pack delivery is unavailable until configured.", config.hosting.port);
|
||||
AstraPacks.LOG.error(
|
||||
"Set hosting.publicAddress to the public HTTP address (port {}). Pack delivery"
|
||||
+ " is unavailable until configured.",
|
||||
config.hosting.port);
|
||||
}
|
||||
AstraPacks.LOG.info("AstraPacks: HTTP port={}, required={}, pack={}",
|
||||
config.hosting.port, config.delivery.required, current == null ? "UNAVAILABLE" : current.path());
|
||||
AstraPacks.LOG.info(
|
||||
"AstraPacks: HTTP port={}, required={}, pack={}",
|
||||
config.hosting.port,
|
||||
config.delivery.required,
|
||||
current == null ? "UNAVAILABLE" : current.path());
|
||||
}
|
||||
|
||||
private PackBuilder.Pack loadStartupPack() {
|
||||
@@ -73,7 +83,8 @@ public final class PackRuntime implements AutoCloseable {
|
||||
try {
|
||||
return new PackBuilder(config).build(root, RESOURCE_VERSION);
|
||||
} catch (IOException e) {
|
||||
AstraPacks.LOG.error("Resource-pack build failed; trying the last successful build", e);
|
||||
AstraPacks.LOG.error(
|
||||
"Resource-pack build failed; trying the last successful build", e);
|
||||
}
|
||||
}
|
||||
try {
|
||||
@@ -101,17 +112,19 @@ public final class PackRuntime implements AutoCloseable {
|
||||
return session;
|
||||
}
|
||||
|
||||
public boolean intercept(ServerCommonPacketListenerImpl listener, ServerboundResourcePackPacket packet) {
|
||||
public boolean intercept(
|
||||
ServerCommonPacketListenerImpl listener, ServerboundResourcePackPacket packet) {
|
||||
if (!config.enabled) {
|
||||
return false;
|
||||
}
|
||||
// Consume stale replies too: vanilla treats any terminal UUID as completion of its task.
|
||||
server.execute(() -> {
|
||||
PackSession session = sessions.get(listener);
|
||||
if (session != null) {
|
||||
session.response(packet);
|
||||
}
|
||||
});
|
||||
server.execute(
|
||||
() -> {
|
||||
PackSession session = sessions.get(listener);
|
||||
if (session != null) {
|
||||
session.response(packet);
|
||||
}
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -150,7 +163,8 @@ public final class PackRuntime implements AutoCloseable {
|
||||
public String url(PackBuilder.Pack pack) {
|
||||
String address = config.hosting.publicAddress;
|
||||
if (address.isBlank()) {
|
||||
throw new IllegalStateException("Set hosting.publicAddress before sending resource packs");
|
||||
throw new IllegalStateException(
|
||||
"Set hosting.publicAddress before sending resource packs");
|
||||
}
|
||||
return address.replaceAll("/+$", "") + host.issuePath(pack);
|
||||
}
|
||||
@@ -174,27 +188,36 @@ public final class PackRuntime implements AutoCloseable {
|
||||
}
|
||||
|
||||
building = true;
|
||||
source.sendSuccess(() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
|
||||
source.sendSuccess(
|
||||
() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
|
||||
worker.execute(() -> preparePack(source, reload));
|
||||
}
|
||||
|
||||
private void preparePack(CommandSourceStack source, boolean reload) {
|
||||
try {
|
||||
PackConfig next = reload ? PackConfig.load(configPath) : config;
|
||||
if (next.enabled != config.enabled || !next.hosting.sameSettings(config.hosting)
|
||||
if (next.enabled != config.enabled
|
||||
|| !next.hosting.sameSettings(config.hosting)
|
||||
|| !next.build.storageDirectory.equals(config.build.storageDirectory)) {
|
||||
throw new IOException("Изменение enabled, каталога хранения или настроек HTTP-сервера требует перезапуска.");
|
||||
throw new IOException(
|
||||
"Изменение enabled, каталога хранения или настроек HTTP-сервера требует"
|
||||
+ " перезапуска.");
|
||||
}
|
||||
PackBuilder.Pack pack = new PackBuilder(next).build(root, RESOURCE_VERSION);
|
||||
server.execute(() -> publishPack(source, next, pack));
|
||||
} catch (Exception e) {
|
||||
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
|
||||
server.execute(() -> {
|
||||
building = false;
|
||||
if (!closed) {
|
||||
source.sendFailure(Component.literal("AstraPacks: " + e.getMessage() + " Рабочий пак сохранён."));
|
||||
}
|
||||
});
|
||||
server.execute(
|
||||
() -> {
|
||||
building = false;
|
||||
if (!closed) {
|
||||
source.sendFailure(
|
||||
Component.literal(
|
||||
"AstraPacks: "
|
||||
+ e.getMessage()
|
||||
+ " Рабочий пак сохранён."));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,8 +230,13 @@ public final class PackRuntime implements AutoCloseable {
|
||||
host.publish(pack);
|
||||
current = pack;
|
||||
|
||||
String message = "AstraPacks: готово, " + pack.files() + " файлов, "
|
||||
+ pack.bytes() + " байт. SHA-1: " + pack.sha1();
|
||||
String message =
|
||||
"AstraPacks: готово, "
|
||||
+ pack.files()
|
||||
+ " файлов, "
|
||||
+ pack.bytes()
|
||||
+ " байт. SHA-1: "
|
||||
+ pack.sha1();
|
||||
source.sendSuccess(() -> Component.literal(message), true);
|
||||
if (config.enabled && config.build.resendAfterBuild) {
|
||||
for (ServerPlayer player : server.getPlayerList().getPlayers()) {
|
||||
@@ -218,10 +246,22 @@ public final class PackRuntime implements AutoCloseable {
|
||||
}
|
||||
|
||||
public String status() {
|
||||
String pack = current == null ? "UNAVAILABLE" : current.path() + " (" + current.files() + " files)";
|
||||
String address = config.hosting.publicAddress.isBlank() ? "NOT SET" : config.hosting.publicAddress;
|
||||
return "AstraPacks HTTP:" + config.hosting.port + ", address=" + address + ", required=" + config.delivery.required
|
||||
+ ", build=" + building + ", pack=" + pack;
|
||||
String pack =
|
||||
current == null
|
||||
? "UNAVAILABLE"
|
||||
: current.path() + " (" + current.files() + " files)";
|
||||
String address =
|
||||
config.hosting.publicAddress.isBlank() ? "NOT SET" : config.hosting.publicAddress;
|
||||
return "AstraPacks HTTP:"
|
||||
+ config.hosting.port
|
||||
+ ", address="
|
||||
+ address
|
||||
+ ", required="
|
||||
+ config.delivery.required
|
||||
+ ", build="
|
||||
+ building
|
||||
+ ", pack="
|
||||
+ pack;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.network.protocol.Packet;
|
||||
import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket;
|
||||
@@ -12,7 +8,13 @@ import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
||||
import net.minecraft.server.network.ConfigurationTask;
|
||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||
|
||||
/** Keeps the configuration task open until the client reports a loaded pack or an allowed failure. */
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Keeps the configuration task open until the client reports a loaded pack or an allowed failure.
|
||||
*/
|
||||
public final class PackSession implements ConfigurationTask {
|
||||
public static final Type TYPE = new Type("astrapacks:resource_pack");
|
||||
|
||||
@@ -59,8 +61,9 @@ public final class PackSession implements ConfigurationTask {
|
||||
prompt = Optional.of(PackText.of(config.messages.prompt, playerName()));
|
||||
}
|
||||
String url = runtime.url(pack);
|
||||
listener.send(new ClientboundResourcePackPushPacket(
|
||||
requestId, url, pack.sha1(), config.delivery.required, prompt));
|
||||
listener.send(
|
||||
new ClientboundResourcePackPushPacket(
|
||||
requestId, url, pack.sha1(), config.delivery.required, prompt));
|
||||
} catch (RuntimeException e) {
|
||||
AstraPacks.LOG.error("Cannot send resource pack to {}", playerName(), e);
|
||||
fail(config.messages.unavailable);
|
||||
@@ -72,7 +75,8 @@ public final class PackSession implements ConfigurationTask {
|
||||
return;
|
||||
}
|
||||
if (config.delivery.logStatus) {
|
||||
AstraPacks.LOG.info("Resource pack {}: {} ({})", playerName(), packet.action(), pack.sha1());
|
||||
AstraPacks.LOG.info(
|
||||
"Resource pack {}: {} ({})", playerName(), packet.action(), pack.sha1());
|
||||
}
|
||||
switch (packet.action()) {
|
||||
case SUCCESSFULLY_LOADED -> {
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
package online.astradev.packs.mixin;
|
||||
|
||||
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||
import online.astradev.packs.PackRuntime;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ServerCommonPacketListenerImpl.class)
|
||||
public abstract class CommonResponseMixin {
|
||||
@Inject(method = "handleResourcePackResponse", at = @At("HEAD"), cancellable = true)
|
||||
private void astrapacks$handleResponse(ServerboundResourcePackPacket packet, CallbackInfo callback) {
|
||||
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||
if (runtime == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// At runtime, this mixin is part of the Minecraft listener.
|
||||
var listener = (ServerCommonPacketListenerImpl) (Object) this;
|
||||
if (runtime.intercept(listener, packet)) {
|
||||
callback.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
-3
@@ -3,16 +3,19 @@ package online.astradev.packs.mixin;
|
||||
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
|
||||
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
|
||||
import net.minecraft.server.network.ServerConfigurationPacketListenerImpl;
|
||||
|
||||
import online.astradev.packs.PackRuntime;
|
||||
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ServerConfigurationPacketListenerImpl.class)
|
||||
public abstract class ConfigurationResponseMixin {
|
||||
@Mixin({ServerCommonPacketListenerImpl.class, ServerConfigurationPacketListenerImpl.class})
|
||||
public abstract class ResourcePackResponseMixin {
|
||||
@Inject(method = "handleResourcePackResponse", at = @At("HEAD"), cancellable = true)
|
||||
private void astrapacks$handleResponse(ServerboundResourcePackPacket packet, CallbackInfo callback) {
|
||||
private void astrapacks$handleResponse(
|
||||
ServerboundResourcePackPacket packet, CallbackInfo callback) {
|
||||
PackRuntime runtime = PackRuntime.INSTANCE;
|
||||
if (runtime == null) {
|
||||
return;
|
||||
@@ -2,6 +2,6 @@
|
||||
"required": true,
|
||||
"package": "online.astradev.packs.mixin",
|
||||
"compatibilityLevel": "JAVA_25",
|
||||
"mixins": ["CommonResponseMixin", "ConfigurationResponseMixin"],
|
||||
"mixins": ["ResourcePackResponseMixin"],
|
||||
"injectors": { "defaultRequire": 1 }
|
||||
}
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
@@ -17,12 +24,6 @@ import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PackCoreTest {
|
||||
@TempDir Path root;
|
||||
|
||||
@@ -45,7 +46,8 @@ class PackCoreTest {
|
||||
private Set<String> archives() throws IOException {
|
||||
try (var files = Files.list(root.resolve("astrapacks/output"))) {
|
||||
return files.filter(path -> path.toString().endsWith(".zip"))
|
||||
.map(path -> path.getFileName().toString()).collect(Collectors.toSet());
|
||||
.map(path -> path.getFileName().toString())
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,8 +76,12 @@ class PackCoreTest {
|
||||
assertNotNull(zip.getEntry("assets/astrasoups/lang/ru_ru.json"));
|
||||
assertNotNull(zip.getEntry("pack.png"));
|
||||
assertNull(zip.getEntry("notes.txt"));
|
||||
String metadata = new String(zip.getInputStream(zip.getEntry("pack.mcmeta")).readAllBytes(), StandardCharsets.UTF_8);
|
||||
var settings = JsonParser.parseString(metadata).getAsJsonObject().getAsJsonObject("pack");
|
||||
String metadata =
|
||||
new String(
|
||||
zip.getInputStream(zip.getEntry("pack.mcmeta")).readAllBytes(),
|
||||
StandardCharsets.UTF_8);
|
||||
var settings =
|
||||
JsonParser.parseString(metadata).getAsJsonObject().getAsJsonObject("pack");
|
||||
assertEquals(config.build.description, settings.get("description").getAsString());
|
||||
assertEquals(JsonParser.parseString("[88,0]"), settings.get("min_format"));
|
||||
}
|
||||
@@ -111,7 +117,9 @@ class PackCoreTest {
|
||||
assertEquals(Set.of(second.sha1() + ".zip", third.sha1() + ".zip"), archives());
|
||||
assertEquals(third.sha1(), PackBuilder.latest(root, config).sha1());
|
||||
assertEquals(third.sha1(), build(config).sha1());
|
||||
assertTrue(Files.exists(second.path()), "An unchanged build must not evict the previous version");
|
||||
assertTrue(
|
||||
Files.exists(second.path()),
|
||||
"An unchanged build must not evict the previous version");
|
||||
asset("assets/demo/test.txt", "second");
|
||||
assertEquals(second.sha1(), build(config).sha1());
|
||||
assertEquals(Set.of(second.sha1() + ".zip", third.sha1() + ".zip"), archives());
|
||||
@@ -136,8 +144,13 @@ class PackCoreTest {
|
||||
@Test
|
||||
void ignoresJarBundlesNestedZipsAndNamedPackRoots() throws Exception {
|
||||
PackConfig config = config();
|
||||
zip(root.resolve("mods/example.jar"), Map.of("astra-pack.properties", "schema=2",
|
||||
"astra-resourcepack/assets/demo/jar.txt", "ignored"));
|
||||
zip(
|
||||
root.resolve("mods/example.jar"),
|
||||
Map.of(
|
||||
"astra-pack.properties",
|
||||
"schema=2",
|
||||
"astra-resourcepack/assets/demo/jar.txt",
|
||||
"ignored"));
|
||||
zip(config.contents(root).resolve("other.zip"), Map.of("assets/demo/zip.txt", "ignored"));
|
||||
asset("other/assets/demo/nested.txt", "ignored");
|
||||
assertEquals(1, build(config).files());
|
||||
@@ -231,7 +244,8 @@ class PackCoreTest {
|
||||
try (var reservation = new ServerSocket(0)) {
|
||||
config.hosting.port = reservation.getLocalPort();
|
||||
}
|
||||
try (PackHost host = new PackHost(config.hosting); HttpClient client = HttpClient.newHttpClient()) {
|
||||
try (PackHost host = new PackHost(config.hosting);
|
||||
HttpClient client = HttpClient.newHttpClient()) {
|
||||
var first = build(config);
|
||||
host.publish(first);
|
||||
host.start();
|
||||
@@ -241,7 +255,10 @@ class PackCoreTest {
|
||||
var second = build(config);
|
||||
host.publish(second);
|
||||
String secondUrl = base + host.issuePath(second);
|
||||
var response = client.send(HttpRequest.newBuilder(URI.create(firstUrl)).build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
var response =
|
||||
client.send(
|
||||
HttpRequest.newBuilder(URI.create(firstUrl)).build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray());
|
||||
assertArrayEquals(Files.readAllBytes(first.path()), response.body());
|
||||
asset("assets/demo/test.txt", "third");
|
||||
var third = build(config);
|
||||
@@ -249,10 +266,15 @@ class PackCoreTest {
|
||||
assertEquals(404, get(client, firstUrl).statusCode());
|
||||
assertEquals(200, get(client, secondUrl).statusCode());
|
||||
String currentUrl = base + host.issuePath(third);
|
||||
var head = client.send(HttpRequest.newBuilder(URI.create(currentUrl))
|
||||
.method("HEAD", HttpRequest.BodyPublishers.noBody()).build(), HttpResponse.BodyHandlers.discarding());
|
||||
var head =
|
||||
client.send(
|
||||
HttpRequest.newBuilder(URI.create(currentUrl))
|
||||
.method("HEAD", HttpRequest.BodyPublishers.noBody())
|
||||
.build(),
|
||||
HttpResponse.BodyHandlers.discarding());
|
||||
assertEquals(200, head.statusCode());
|
||||
assertEquals(third.bytes(), head.headers().firstValueAsLong("Content-Length").orElseThrow());
|
||||
assertEquals(
|
||||
third.bytes(), head.headers().firstValueAsLong("Content-Length").orElseThrow());
|
||||
assertEquals(403, get(client, currentUrl.split("\\?")[0]).statusCode());
|
||||
assertEquals(404, get(client, base + "/server.properties").statusCode());
|
||||
}
|
||||
@@ -282,25 +304,37 @@ class PackCoreTest {
|
||||
asset("assets/demo/data.bin", "");
|
||||
Files.write(config.contents(root).resolve("assets/demo/data.bin"), content);
|
||||
var pack = build(config);
|
||||
try (PackHost host = new PackHost(config.hosting); HttpClient client = HttpClient.newHttpClient()) {
|
||||
try (PackHost host = new PackHost(config.hosting);
|
||||
HttpClient client = HttpClient.newHttpClient()) {
|
||||
host.publish(pack);
|
||||
host.start();
|
||||
URI uri = URI.create("http://127.0.0.1:" + config.hosting.port + host.issuePath(pack));
|
||||
long started = System.nanoTime();
|
||||
var download = client.send(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.ofInputStream());
|
||||
var download =
|
||||
client.send(
|
||||
HttpRequest.newBuilder(uri).build(),
|
||||
HttpResponse.BodyHandlers.ofInputStream());
|
||||
assertEquals(200, download.statusCode());
|
||||
try (var body = download.body()) {
|
||||
assertEquals(429, get(client, uri.toString()).statusCode());
|
||||
assertArrayEquals(Files.readAllBytes(pack.path()), body.readAllBytes());
|
||||
}
|
||||
assertTrue(System.nanoTime() - started >= 900_000_000L, "Transfer must respect the configured speed");
|
||||
var head = client.send(HttpRequest.newBuilder(uri).method("HEAD", HttpRequest.BodyPublishers.noBody()).build(),
|
||||
HttpResponse.BodyHandlers.discarding());
|
||||
assertTrue(
|
||||
System.nanoTime() - started >= 900_000_000L,
|
||||
"Transfer must respect the configured speed");
|
||||
var head =
|
||||
client.send(
|
||||
HttpRequest.newBuilder(uri)
|
||||
.method("HEAD", HttpRequest.BodyPublishers.noBody())
|
||||
.build(),
|
||||
HttpResponse.BodyHandlers.discarding());
|
||||
assertEquals(200, head.statusCode(), "Completed downloads must release their slot");
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpResponse<Void> get(HttpClient client, String url) throws Exception {
|
||||
return client.send(HttpRequest.newBuilder(URI.create(url)).build(), HttpResponse.BodyHandlers.discarding());
|
||||
return client.send(
|
||||
HttpRequest.newBuilder(URI.create(url)).build(),
|
||||
HttpResponse.BodyHandlers.discarding());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user