Expose asynchronous publication receipts, roll back failed prepared inputs, and preserve the active pack across failed builds and shutdown.
408 lines
16 KiB
Java
408 lines
16 KiB
Java
package online.astradev.packs;
|
|
|
|
import com.sun.net.httpserver.HttpHandler;
|
|
|
|
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 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.CompletableFuture;
|
|
import java.util.concurrent.Callable;
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
import java.util.concurrent.Executor;
|
|
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.Executors;
|
|
import java.util.function.Consumer;
|
|
|
|
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;
|
|
private final Executor callbacks;
|
|
|
|
private volatile PackConfig config;
|
|
private volatile PackBuilder.Pack current;
|
|
private volatile boolean closed;
|
|
// Only the server thread changes this flag, including publication and failure callbacks.
|
|
private volatile boolean building;
|
|
private CompletableFuture<String> activeBuild;
|
|
private BuildInputs activeInputs;
|
|
|
|
public PackRuntime(MinecraftServer server, Path root, Path configPath, PackConfig config) {
|
|
this(server, root, configPath, config,
|
|
Executors.newSingleThreadExecutor(Thread.ofPlatform().daemon().name("AstraPacks-build").factory()),
|
|
server::execute);
|
|
}
|
|
|
|
PackRuntime(MinecraftServer server, Path root, Path configPath, PackConfig config,
|
|
ExecutorService worker, Executor callbacks) {
|
|
this.server = server;
|
|
this.root = root;
|
|
this.configPath = configPath;
|
|
this.config = config;
|
|
this.host = new PackHost(config.hosting);
|
|
this.worker = worker;
|
|
this.callbacks = callbacks;
|
|
}
|
|
|
|
public void start() throws IOException {
|
|
if (!config.enabled) {
|
|
return;
|
|
}
|
|
if (server.getServerResourcePack().isPresent()) {
|
|
throw new IOException(
|
|
"AstraPacks must be the only pack sender: clear resource-pack in"
|
|
+ " server.properties");
|
|
}
|
|
|
|
Files.createDirectories(config.contents(root));
|
|
PackBuilder.Pack pack = loadStartupPack();
|
|
if (pack != null) {
|
|
host.publish(pack);
|
|
current = pack;
|
|
}
|
|
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.info(
|
|
"AstraPacks: HTTP port={}, required={}, pack={}",
|
|
config.hosting.port,
|
|
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.latest(root, config);
|
|
} catch (IOException e) {
|
|
AstraPacks.LOG.error("No usable pack. Required-pack logins will be refused.", e);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public PackConfig config() {
|
|
return config;
|
|
}
|
|
|
|
public PackBuilder.Pack current() {
|
|
return current;
|
|
}
|
|
|
|
public PackSession session(ServerCommonPacketListenerImpl listener) {
|
|
PackSession session = new PackSession(this, listener);
|
|
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;
|
|
}
|
|
// 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() {
|
|
var iterator = sessions.entrySet().iterator();
|
|
while (iterator.hasNext()) {
|
|
var entry = iterator.next();
|
|
ServerCommonPacketListenerImpl listener = entry.getKey();
|
|
Connection connection = listener.getConnection();
|
|
if (connection.isConnected()) {
|
|
entry.getValue().tick();
|
|
} else {
|
|
pendingWelcome.remove(listener.getOwner().id());
|
|
iterator.remove();
|
|
}
|
|
}
|
|
}
|
|
|
|
public void loaded(ServerCommonPacketListenerImpl listener, String message) {
|
|
if (listener instanceof ServerGamePacketListenerImpl game) {
|
|
if (!message.isBlank()) {
|
|
game.player.sendSystemMessage(PackText.of(message, listener.getOwner().name()));
|
|
}
|
|
} else {
|
|
pendingWelcome.put(listener.getOwner().id(), message);
|
|
}
|
|
}
|
|
|
|
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(PackBuilder.Pack pack) {
|
|
String address = config.hosting.publicAddress;
|
|
if (address.isBlank()) {
|
|
throw new IllegalStateException(
|
|
"Set hosting.publicAddress before sending resource packs");
|
|
}
|
|
return address.replaceAll("/+$", "") + host.issuePath(pack);
|
|
}
|
|
|
|
/** Mounts an editor or other web endpoint on AstraPacks' HTTP origin. */
|
|
public AutoCloseable mountWebContext(String prefix, HttpHandler handler) {
|
|
if (closed) {
|
|
throw new IllegalStateException("AstraPacks is closed");
|
|
}
|
|
return host.mountWebContext(prefix, handler);
|
|
}
|
|
|
|
public String publicUrl(String path) {
|
|
return host.publicUrl(config.hosting.publicAddress, path);
|
|
}
|
|
|
|
public void build(CommandSourceStack source) {
|
|
buildAsync(source);
|
|
}
|
|
|
|
/** Completes after the archive becomes the server's current pack, not after client acceptance. */
|
|
public CompletableFuture<String> buildAsync(CommandSourceStack source) {
|
|
return buildAsync(source, () -> () -> {});
|
|
}
|
|
|
|
/** Reserves the build before changing shared inputs; the receipt restores them on failure. */
|
|
public CompletableFuture<String> buildAsync(CommandSourceStack source, Callable<AutoCloseable> prepareInputs) {
|
|
return requestBuild(false, message -> source.sendSuccess(() -> Component.literal(message), false),
|
|
message -> source.sendFailure(Component.literal(message)), prepareInputs);
|
|
}
|
|
|
|
public void reload(CommandSourceStack source) {
|
|
requestBuild(true, message -> source.sendSuccess(() -> Component.literal(message), false),
|
|
message -> source.sendFailure(Component.literal(message)));
|
|
}
|
|
|
|
synchronized CompletableFuture<String> requestBuild(boolean reload, Consumer<String> success, Consumer<String> failure) {
|
|
return requestBuild(reload, success, failure, () -> () -> {});
|
|
}
|
|
|
|
synchronized CompletableFuture<String> requestBuild(boolean reload, Consumer<String> success,
|
|
Consumer<String> failure, Callable<AutoCloseable> prepareInputs) {
|
|
if (closed) {
|
|
return rejected("AstraPacks остановлен.", failure);
|
|
}
|
|
if (!config.enabled) return rejected("AstraPacks отключён: публикация ресурспака недоступна.", failure);
|
|
if (building) {
|
|
return rejected("Сборка AstraPacks уже выполняется.", failure);
|
|
}
|
|
|
|
var inputs = new BuildInputs(prepareInputs);
|
|
building = true;
|
|
var result = new CompletableFuture<String>();
|
|
activeBuild = result;
|
|
activeInputs = inputs;
|
|
try {
|
|
success.accept("AstraPacks: проверка и подготовка ресурспака…");
|
|
worker.execute(() -> preparePack(result, inputs, reload, success, failure));
|
|
} catch (RuntimeException error) {
|
|
failBuild(result, error, failure);
|
|
}
|
|
return result.copy();
|
|
}
|
|
|
|
private static CompletableFuture<String> rejected(String message, Consumer<String> failure) {
|
|
failure.accept(message);
|
|
return CompletableFuture.failedFuture(new IllegalStateException(message));
|
|
}
|
|
|
|
private void preparePack(CompletableFuture<String> result, BuildInputs inputs, boolean reload,
|
|
Consumer<String> success, Consumer<String> failure) {
|
|
PackBuilder.Prepared prepared = null;
|
|
try {
|
|
if (closed || result.isDone()) return;
|
|
PackConfig next = reload ? PackConfig.load(configPath) : config;
|
|
if (next.enabled != config.enabled
|
|
|| !next.hosting.sameSettings(config.hosting)
|
|
|| !next.build.storageDirectory.equals(config.build.storageDirectory)) {
|
|
throw new IOException(
|
|
"Изменение enabled, каталога хранения или настроек HTTP-сервера требует"
|
|
+ " перезапуска.");
|
|
}
|
|
inputs.prepare();
|
|
prepared = new PackBuilder(next).prepare(root, RESOURCE_VERSION);
|
|
var candidate = prepared;
|
|
callbacks.execute(() -> publishPack(result, next, candidate, success, failure));
|
|
} catch (Exception e) {
|
|
discard(prepared, e);
|
|
Exception error = rollbackInputs(inputs, e);
|
|
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", error);
|
|
try { callbacks.execute(() -> failBuild(result, error, failure)); }
|
|
catch (RuntimeException unavailable) {
|
|
error.addSuppressed(unavailable);
|
|
failBuild(result, error, ignored -> {});
|
|
}
|
|
}
|
|
}
|
|
|
|
private synchronized void failBuild(CompletableFuture<String> result, Exception error, Consumer<String> failure) {
|
|
if (activeBuild != result) return;
|
|
error = rollbackInputs(activeInputs, error);
|
|
building = false;
|
|
activeBuild = null;
|
|
activeInputs = null;
|
|
result.completeExceptionally(error);
|
|
if (closed) return;
|
|
String message = "AstraPacks: " + error.getMessage() + " Рабочий пак сохранён.";
|
|
failure.accept(message);
|
|
}
|
|
|
|
private synchronized void publishPack(CompletableFuture<String> result, PackConfig next, PackBuilder.Prepared prepared,
|
|
Consumer<String> success, Consumer<String> failure) {
|
|
if (closed || activeBuild != result) {
|
|
discard(prepared, null);
|
|
return;
|
|
}
|
|
var pack = prepared.pack();
|
|
try {
|
|
host.publish(pack);
|
|
new PackBuilder(next).publish(root, prepared);
|
|
activeInputs.commit();
|
|
config = next;
|
|
current = pack;
|
|
} catch (IOException | RuntimeException error) {
|
|
discard(prepared, error);
|
|
failBuild(result, error, failure);
|
|
return;
|
|
}
|
|
String message =
|
|
"AstraPacks: готово, "
|
|
+ pack.files()
|
|
+ " файлов, "
|
|
+ pack.bytes()
|
|
+ " байт. SHA-1: "
|
|
+ pack.sha1();
|
|
building = false;
|
|
activeBuild = null;
|
|
activeInputs = null;
|
|
result.complete(message + ". Пак опубликован; загрузка игроками проверяется отдельно.");
|
|
try { success.accept(message); }
|
|
catch (RuntimeException notification) { AstraPacks.LOG.warn("Pack published, but build notification failed", notification); }
|
|
if (config.enabled && config.build.resendAfterBuild) {
|
|
try {
|
|
for (ServerPlayer player : server.getPlayerList().getPlayers()) {
|
|
try { session(player.connection).start(player.connection::send); }
|
|
catch (RuntimeException delivery) { AstraPacks.LOG.warn("Pack published, but delivery failed for {}", player.getUUID(), delivery); }
|
|
}
|
|
} catch (RuntimeException delivery) { AstraPacks.LOG.warn("Pack published, but starting delivery failed", delivery); }
|
|
}
|
|
}
|
|
|
|
private static void discard(PackBuilder.Prepared prepared, Exception failure) {
|
|
try { PackBuilder.discard(prepared); }
|
|
catch (IOException cleanup) {
|
|
if (failure != null) failure.addSuppressed(cleanup);
|
|
else AstraPacks.LOG.warn("Cannot remove unpublished pack candidate", cleanup);
|
|
}
|
|
}
|
|
|
|
private static Exception rollbackInputs(BuildInputs inputs, Exception failure) {
|
|
if (inputs == null) return failure;
|
|
try { inputs.rollback(); return failure; }
|
|
catch (Exception rollback) {
|
|
var combined = new IOException(failure.getMessage() + "; не удалось восстановить исходные ресурсы: " + rollback.getMessage(), failure);
|
|
combined.addSuppressed(rollback);
|
|
return combined;
|
|
}
|
|
}
|
|
|
|
/** Close waits for an in-progress export before restoring its files; publication commits once. */
|
|
private static final class BuildInputs {
|
|
private final Callable<AutoCloseable> prepare;
|
|
private AutoCloseable receipt;
|
|
private boolean finished;
|
|
|
|
BuildInputs(Callable<AutoCloseable> prepare) { this.prepare = java.util.Objects.requireNonNull(prepare); }
|
|
synchronized void prepare() throws Exception {
|
|
if (finished) throw new IllegalStateException("Resource input preparation was stopped");
|
|
receipt = java.util.Objects.requireNonNull(prepare.call(), "Input preparation must return a rollback receipt");
|
|
}
|
|
synchronized void commit() { finished = true; receipt = null; }
|
|
synchronized void rollback() throws Exception {
|
|
if (finished) return;
|
|
finished = true;
|
|
if (receipt != null) receipt.close();
|
|
receipt = null;
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
@Override
|
|
public synchronized void close() {
|
|
closed = true;
|
|
building = false;
|
|
if (activeBuild != null) {
|
|
var failure = rollbackInputs(activeInputs, new IllegalStateException("AstraPacks остановлен до завершения публикации."));
|
|
activeBuild.completeExceptionally(failure);
|
|
activeBuild = null;
|
|
activeInputs = null;
|
|
}
|
|
worker.shutdownNow();
|
|
host.close();
|
|
sessions.clear();
|
|
pendingWelcome.clear();
|
|
}
|
|
}
|