Simplify pack delivery, build lifecycle and HTTP handling; remove project clutter

This commit is contained in:
2026-09-06 18:28:23 +03:00
parent 09d002987f
commit e924cf26a5
13 changed files with 800 additions and 566 deletions
@@ -1,19 +1,25 @@
package online.astradev.packs;
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.Connection;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
import online.astradev.packs.mixin.CommonAccessor;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
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;
private final MinecraftServer server;
@@ -22,113 +28,236 @@ public final class PackRuntime implements AutoCloseable {
private volatile PackConfig config;
private volatile PackBuilder.Pack current;
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> welcome = new ConcurrentHashMap<>();
private final ExecutorService worker = Executors.newSingleThreadExecutor(Thread.ofPlatform().daemon().name("AstraPacks-build").factory());
private final AtomicBoolean busy = new AtomicBoolean();
private final ExecutorService worker =
Executors.newSingleThreadExecutor(
Thread.ofPlatform().daemon().name("AstraPacks-build").factory());
// Read and written on the server thread, including build completion callbacks.
private boolean busy;
private volatile boolean closed;
public PackRuntime(MinecraftServer server, Path root, Path configPath, PackConfig config) {
this.server = server; this.root = root; this.configPath = configPath; this.config = config;
this.server = server;
this.root = root;
this.configPath = configPath;
this.config = config;
this.host = new PackHost(config.hosting);
}
public void start() throws Exception {
if (!config.enabled) 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");
// Only create the default source automatically. A typo in a custom path must fail visibly.
Files.createDirectories(root.resolve("astrapacks/contents"));
PackBuilder.Pack candidate;
try { candidate = config.build.onStartup ? new PackBuilder(config).build(root, "[88,0]") : PackBuilder.previous(root, config); }
catch (IOException e) {
try {
candidate =
config.build.onStartup
? new PackBuilder(config).build(root, "[88,0]")
: PackBuilder.previous(root, config);
} catch (IOException e) {
AstraPacks.LOG.error("Resource-pack build failed; trying the last successful build", e);
try { candidate = PackBuilder.previous(root, config); }
catch (IOException absent) { AstraPacks.LOG.error("No usable pack. Required-pack logins will be refused.", absent); candidate = null; }
try {
candidate = PackBuilder.previous(root, config);
} catch (IOException absent) {
AstraPacks.LOG.error(
"No usable pack. Required-pack logins will be refused.", absent);
candidate = null;
}
}
if (candidate != null) {
try { PackBuilder.verifyExternal(config, candidate); current = candidate; host.publish(candidate); }
catch (IOException e) { AstraPacks.LOG.error("External ZIP is not ready. Required-pack logins will be refused.", e); }
try {
PackBuilder.verifyExternal(config, candidate);
current = candidate;
host.publish(candidate);
} catch (IOException e) {
AstraPacks.LOG.error(
"External ZIP is not ready. Required-pack logins will be refused.", e);
}
}
host.start();
AstraPacks.LOG.info("AstraPacks: mode={}, required={}, pack={}", config.hosting.mode, config.delivery.required, current == null ? "UNAVAILABLE" : current.path());
AstraPacks.LOG.info(
"AstraPacks: mode={}, required={}, pack={}",
config.hosting.mode,
config.delivery.required,
current == null ? "UNAVAILABLE" : current.path());
}
public PackConfig config() { return config; }
public PackBuilder.Pack current() { return current; }
public PackHost host() { return host; }
public PackConfig config() {
return config;
}
public PackBuilder.Pack current() {
return current;
}
public PackHost host() {
return host;
}
public PackSession session(ServerCommonPacketListenerImpl listener) {
PackSession session = new PackSession(this, listener);
PackSession old = sessions.put(listener, session);
if (old != null) old.replace();
return session;
}
public boolean intercept(ServerCommonPacketListenerImpl listener, ServerboundResourcePackPacket packet) {
public boolean intercept(
ServerCommonPacketListenerImpl listener, ServerboundResourcePackPacket packet) {
if (!config.enabled) return false;
// Vanilla configuration handling finishes its own task for ANY terminal UUID.
// Consume unrelated/stale replies too, so they cannot finish our gate or another 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;
}
public void tick() {
sessions.entrySet().removeIf(entry -> {
if (!((CommonAccessor)entry.getKey()).astrapacks$connection().isConnected()) {
welcome.remove(entry.getKey().getOwner().id());
return true;
}
entry.getValue().tick(); return false;
});
sessions.entrySet()
.removeIf(
entry -> {
if (!((CommonAccessor) entry.getKey())
.astrapacks$connection()
.isConnected()) {
welcome.remove(entry.getKey().getOwner().id());
return true;
}
entry.getValue().tick();
return false;
});
}
public void loaded(ServerCommonPacketListenerImpl listener, String message) {
if (listener instanceof net.minecraft.server.network.ServerGamePacketListenerImpl game) {
if (!message.isBlank()) game.player.sendSystemMessage(PackText.of(message, listener.getOwner().name()));
if (!message.isBlank())
game.player.sendSystemMessage(PackText.of(message, listener.getOwner().name()));
} else welcome.put(listener.getOwner().id(), message);
}
public void welcome(net.minecraft.server.level.ServerPlayer player) {
String text = welcome.remove(player.getUUID());
if (text != null && !text.isBlank()) player.sendSystemMessage(PackText.of(text, player.getGameProfile().name()));
if (text != null && !text.isBlank())
player.sendSystemMessage(PackText.of(text, player.getGameProfile().name()));
}
public String url(ServerCommonPacketListenerImpl listener, PackBuilder.Pack pack) {
if (config.hosting.mode.equals("no_host")) return config.hosting.externalUrl;
Connection connection = ((CommonAccessor)listener).astrapacks$connection();
Connection connection = ((CommonAccessor) listener).astrapacks$connection();
String base = config.hosting.publicAddress;
if (base.equals("auto")) {
String address = ((ConnectionData)connection).astrapacks$host();
if (address == null || address.isBlank()) throw new IllegalArgumentException("Cannot determine server address; set hosting.publicAddress");
int port = config.hosting.mode.equals("self_host") ? config.hosting.port : server.getPort();
try { base = new URI("http", null, address, port, null, null, null).toASCIIString(); }
catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid server address", e); }
String address = ((ConnectionData) connection).astrapacks$host();
if (address == null || address.isBlank())
throw new IllegalArgumentException(
"Cannot determine server address; set hosting.publicAddress");
int port =
config.hosting.mode.equals("self_host")
? config.hosting.port
: server.getPort();
try {
base = new URI("http", null, address, port, null, null, null).toASCIIString();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid server address", e);
}
}
return base.replaceAll("/+$", "") + host.issuePath(pack);
}
public void rebuild(CommandSourceStack source, boolean reload, boolean publishOnly) {
if (!busy.compareAndSet(false, true)) { source.sendFailure(Component.literal("Сборка AstraPacks уже выполняется.")); return; }
source.sendSuccess(() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
worker.submit(() -> {
try {
PackConfig next = reload ? PackConfig.load(configPath) : config;
if (next.enabled != config.enabled || !PackConfig.JSON.toJson(next.hosting).equals(PackConfig.JSON.toJson(config.hosting)))
throw new IOException("Изменение enabled или hosting требует перезапуска сервера.");
PackBuilder.Pack pack = publishOnly ? PackBuilder.previous(root, next) : new PackBuilder(next).build(root, "[88,0]");
PackBuilder.verifyExternal(next, pack);
server.execute(() -> {
if (closed) return;
config = next; current = pack; host.publish(pack);
source.sendSuccess(() -> Component.literal("AstraPacks: готово, " + pack.files() + " файлов, " + pack.bytes() + " байт. SHA-1: " + pack.sha1()), true);
if (config.enabled && config.build.resendAfterBuild) resendAll();
});
} catch (Exception e) {
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
server.execute(() -> source.sendFailure(Component.literal("AstraPacks: " + e.getMessage() + " Рабочий пак сохранён.")));
} finally { busy.set(false); }
});
if (closed) {
source.sendFailure(Component.literal("AstraPacks остановлен."));
return;
}
if (busy) {
source.sendFailure(Component.literal("Сборка AstraPacks уже выполняется."));
return;
}
busy = true;
source.sendSuccess(
() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
worker.execute(() -> preparePack(source, reload, publishOnly));
}
private void preparePack(CommandSourceStack source, boolean reload, boolean publishOnly) {
try {
PackConfig next = reload ? PackConfig.load(configPath) : config;
if (next.enabled != config.enabled || !next.hosting.sameSettings(config.hosting)) {
throw new IOException("Изменение enabled или hosting требует перезапуска сервера.");
}
PackBuilder.Pack pack =
publishOnly
? PackBuilder.previous(root, next)
: new PackBuilder(next).build(root, "[88,0]");
PackBuilder.verifyExternal(next, pack);
server.execute(() -> publishPack(source, next, pack));
} catch (Exception e) {
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
server.execute(
() -> {
busy = false;
if (!closed) {
source.sendFailure(
Component.literal(
"AstraPacks: "
+ e.getMessage()
+ " Рабочий пак сохранён."));
}
});
}
}
private void publishPack(CommandSourceStack source, PackConfig next, PackBuilder.Pack pack) {
busy = false;
if (closed) {
return;
}
config = next;
current = pack;
host.publish(pack);
String message =
"AstraPacks: готово, "
+ pack.files()
+ " файлов, "
+ pack.bytes()
+ " байт. SHA-1: "
+ pack.sha1();
source.sendSuccess(() -> Component.literal(message), true);
if (config.enabled && config.build.resendAfterBuild) {
resendAll();
}
}
public void resendAll() {
for (var player : server.getPlayerList().getPlayers()) session(player.connection).start(player.connection::send);
for (var player : server.getPlayerList().getPlayers())
session(player.connection).start(player.connection::send);
}
public String status() {
return "AstraPacks " + config.hosting.mode + ", required=" + config.delivery.required
+ ", build=" + busy.get() + ", pack=" + (current == null ? "UNAVAILABLE" : current.path() + " (" + current.files() + " files)");
return "AstraPacks "
+ config.hosting.mode
+ ", required="
+ config.delivery.required
+ ", build="
+ busy
+ ", pack="
+ (current == null
? "UNAVAILABLE"
: current.path() + " (" + current.files() + " files)");
}
@Override
public void close() {
closed = true;
worker.shutdownNow();
host.close();
sessions.clear();
welcome.clear();
}
@Override public void close() { closed = true; worker.shutdownNow(); host.close(); sessions.clear(); welcome.clear(); }
}