Clarify resource build stages, command registration and download flow

This commit is contained in:
2026-09-06 18:36:18 +03:00
parent e924cf26a5
commit 5b51cba772
8 changed files with 762 additions and 655 deletions
@@ -1,14 +1,5 @@
package online.astradev.packs;
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;
@@ -20,23 +11,35 @@ 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;
import net.minecraft.network.protocol.common.ServerboundResourcePackPacket;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.network.ServerCommonPacketListenerImpl;
import net.minecraft.server.network.ServerGamePacketListenerImpl;
import online.astradev.packs.mixin.CommonAccessor;
public final class PackRuntime implements AutoCloseable {
public static volatile PackRuntime INSTANCE;
private static final String RESOURCE_VERSION = "[88,0]";
private final MinecraftServer server;
private final Path root;
private final Path configPath;
private final PackHost host;
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 volatile PackConfig config;
private volatile PackBuilder.Pack current;
private final PackHost host;
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());
// Read and written on the server thread, including build completion callbacks.
private boolean busy;
private volatile boolean closed;
// Only the server thread changes this flag, including publication and failure callbacks.
private boolean building;
public PackRuntime(MinecraftServer server, Path root, Path configPath, PackConfig config) {
this.server = server;
@@ -46,46 +49,46 @@ public final class PackRuntime implements AutoCloseable {
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");
// Only create the default source automatically. A typo in a custom path must fail visibly.
public void start() throws IOException, InterruptedException {
if (!config.enabled) {
return;
}
if (server.getServerResourcePack().isPresent()) {
throw new IOException("AstraPacks must be the only pack sender: clear resource-pack in server.properties");
}
// Custom source paths are not created: a typo in the configuration must be visible.
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) {
AstraPacks.LOG.error("Resource-pack build failed; trying the last successful build", e);
PackBuilder.Pack pack = loadStartupPack();
if (pack != 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);
PackBuilder.verifyExternal(config, pack);
host.publish(pack);
current = pack;
} catch (IOException e) {
AstraPacks.LOG.error(
"External ZIP is not ready. Required-pack logins will be refused.", 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());
}
private PackBuilder.Pack loadStartupPack() {
if (config.build.onStartup) {
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);
}
}
try {
return PackBuilder.previous(root, config);
} catch (IOException e) {
AstraPacks.LOG.error("No usable pack. Required-pack logins will be refused.", e);
return null;
}
}
public PackConfig config() {
@@ -102,86 +105,108 @@ public final class PackRuntime implements AutoCloseable {
public PackSession session(ServerCommonPacketListenerImpl listener) {
PackSession session = new PackSession(this, listener);
PackSession old = sessions.put(listener, session);
if (old != null) old.replace();
PackSession previous = sessions.put(listener, session);
if (previous != null) {
previous.removeFromClient();
}
return session;
}
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);
});
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);
}
});
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;
});
var iterator = sessions.entrySet().iterator();
while (iterator.hasNext()) {
var entry = iterator.next();
ServerCommonPacketListenerImpl listener = entry.getKey();
Connection connection = ((CommonAccessor) listener).astrapacks$connection();
if (connection.isConnected()) {
entry.getValue().tick();
} else {
pendingWelcome.remove(listener.getOwner().id());
iterator.remove();
}
}
}
public void loaded(ServerCommonPacketListenerImpl listener, String message) {
if (listener instanceof net.minecraft.server.network.ServerGamePacketListenerImpl game) {
if (!message.isBlank())
if (listener instanceof ServerGamePacketListenerImpl game) {
if (!message.isBlank()) {
game.player.sendSystemMessage(PackText.of(message, listener.getOwner().name()));
} else welcome.put(listener.getOwner().id(), message);
}
} else {
pendingWelcome.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()));
public void welcome(ServerPlayer player) {
String message = pendingWelcome.remove(player.getUUID());
if (message != null && !message.isBlank()) {
player.sendSystemMessage(PackText.of(message, 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();
if (config.hosting.mode.equals("no_host")) {
return config.hosting.externalUrl;
}
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);
}
base = automaticAddress(listener);
}
return base.replaceAll("/+$", "") + host.issuePath(pack);
}
public void rebuild(CommandSourceStack source, boolean reload, boolean publishOnly) {
private String automaticAddress(ServerCommonPacketListenerImpl listener) {
Connection connection = ((CommonAccessor) listener).astrapacks$connection();
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 {
return new URI("http", null, address, port, null, null, null).toASCIIString();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Invalid server address", e);
}
}
public void build(CommandSourceStack source) {
requestBuild(source, false, false);
}
public void reload(CommandSourceStack source) {
requestBuild(source, true, false);
}
public void publish(CommandSourceStack source) {
requestBuild(source, false, true);
}
private void requestBuild(CommandSourceStack source, boolean reload, boolean publishOnly) {
if (closed) {
source.sendFailure(Component.literal("AstraPacks остановлен."));
return;
}
if (busy) {
if (building) {
source.sendFailure(Component.literal("Сборка AstraPacks уже выполняется."));
return;
}
busy = true;
source.sendSuccess(
() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
building = true;
source.sendSuccess(() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
worker.execute(() -> preparePack(source, reload, publishOnly));
}
@@ -191,65 +216,45 @@ public final class PackRuntime implements AutoCloseable {
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.Pack pack = publishOnly
? PackBuilder.previous(root, next)
: new PackBuilder(next).build(root, RESOURCE_VERSION);
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()
+ " Рабочий пак сохранён."));
}
});
server.execute(() -> {
building = false;
if (!closed) {
source.sendFailure(Component.literal("AstraPacks: " + e.getMessage() + " Рабочий пак сохранён."));
}
});
}
}
private void publishPack(CommandSourceStack source, PackConfig next, PackBuilder.Pack pack) {
busy = false;
building = false;
if (closed) {
return;
}
config = next;
current = pack;
host.publish(pack);
String message =
"AstraPacks: готово, "
+ pack.files()
+ " файлов, "
+ pack.bytes()
+ " байт. SHA-1: "
+ pack.sha1();
current = 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();
for (ServerPlayer player : server.getPlayerList().getPlayers()) {
session(player.connection).start(player.connection::send);
}
}
}
public void resendAll() {
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
+ ", pack="
+ (current == null
? "UNAVAILABLE"
: current.path() + " (" + current.files() + " files)");
String pack = current == null ? "UNAVAILABLE" : current.path() + " (" + current.files() + " files)";
return "AstraPacks " + config.hosting.mode + ", required=" + config.delivery.required
+ ", build=" + building + ", pack=" + pack;
}
@Override
@@ -258,6 +263,6 @@ public final class PackRuntime implements AutoCloseable {
worker.shutdownNow();
host.close();
sessions.clear();
welcome.clear();
pendingWelcome.clear();
}
}