Publish resource packs only after successful reserved builds
Expose asynchronous publication receipts, roll back failed prepared inputs, and preserve the active pack across failed builds and shutdown.
This commit is contained in:
@@ -23,6 +23,7 @@ import java.util.zip.ZipOutputStream;
|
||||
/** 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) {}
|
||||
record Prepared(Pack pack, boolean created) {}
|
||||
|
||||
private final PackConfig config;
|
||||
|
||||
@@ -31,6 +32,19 @@ public final class PackBuilder {
|
||||
}
|
||||
|
||||
public Pack build(Path root, String resourceVersion) throws IOException {
|
||||
Prepared prepared = prepare(root, resourceVersion);
|
||||
try {
|
||||
publish(root, prepared);
|
||||
return prepared.pack();
|
||||
} catch (IOException failure) {
|
||||
try { discard(prepared); }
|
||||
catch (IOException cleanup) { failure.addSuppressed(cleanup); }
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
/** Creates an immutable candidate without changing current.json or pruning active archives. */
|
||||
Prepared prepare(Path root, String resourceVersion) throws IOException {
|
||||
Path contents = config.contents(root);
|
||||
if (!Files.isDirectory(contents)) {
|
||||
throw new IOException("Resource directory is missing: " + contents);
|
||||
@@ -53,25 +67,21 @@ public final class PackBuilder {
|
||||
} else if (!sha1(destination).equals(sha1)) {
|
||||
throw new IOException("Published ZIP was modified: " + destination);
|
||||
}
|
||||
Pack pack = new Pack(destination, sha1, files, Files.size(destination));
|
||||
try {
|
||||
saveCurrent(output, pack);
|
||||
} catch (IOException e) {
|
||||
if (created) {
|
||||
try {
|
||||
Files.deleteIfExists(destination);
|
||||
} catch (IOException cleanupError) {
|
||||
e.addSuppressed(cleanupError);
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
return pack;
|
||||
return new Prepared(new Pack(destination, sha1, files, Files.size(destination)), created);
|
||||
} finally {
|
||||
Files.deleteIfExists(temporary);
|
||||
}
|
||||
}
|
||||
|
||||
/** Called only after the server accepts this candidate as its next active pack. */
|
||||
void publish(Path root, Prepared prepared) throws IOException {
|
||||
saveCurrent(config.storage(root).resolve("output"), prepared.pack());
|
||||
}
|
||||
|
||||
static void discard(Prepared prepared) throws IOException {
|
||||
if (prepared != null && prepared.created()) Files.deleteIfExists(prepared.pack().path());
|
||||
}
|
||||
|
||||
private int writeArchive(Path contents, Path target, String resourceVersion)
|
||||
throws IOException {
|
||||
// Shared with server-side exporters (AstraPlus). A build must see one complete asset
|
||||
@@ -174,6 +184,8 @@ public final class PackBuilder {
|
||||
if (previous != null) {
|
||||
info.addProperty("previousSha1", previous);
|
||||
}
|
||||
// Commit the durable pointer before housekeeping; cleanup failure must not undo publication.
|
||||
PackFiles.atomicWrite(manifest, PackConfig.JSON.toJson(info).getBytes(StandardCharsets.UTF_8));
|
||||
// Only remove generated hash-named ZIPs, never user content or unrelated files.
|
||||
try (var paths = Files.list(output)) {
|
||||
for (Path path : paths.toList()) {
|
||||
@@ -183,9 +195,9 @@ public final class PackBuilder {
|
||||
if (previous != null && name.equals(previous + ".zip")) continue;
|
||||
if (Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) Files.delete(path);
|
||||
}
|
||||
} catch (IOException | RuntimeException cleanup) {
|
||||
AstraPacks.LOG.warn("Pack published; old archive cleanup will be retried on the next build", cleanup);
|
||||
}
|
||||
PackFiles.atomicWrite(
|
||||
manifest, PackConfig.JSON.toJson(info).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static Pack latest(Path root, PackConfig config) throws IOException {
|
||||
|
||||
@@ -16,9 +16,13 @@ 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;
|
||||
@@ -32,22 +36,32 @@ public final class PackRuntime implements AutoCloseable {
|
||||
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;
|
||||
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 boolean building;
|
||||
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 {
|
||||
@@ -184,31 +198,63 @@ public final class PackRuntime implements AutoCloseable {
|
||||
}
|
||||
|
||||
public void build(CommandSourceStack source) {
|
||||
requestBuild(source, false);
|
||||
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(source, true);
|
||||
requestBuild(true, message -> source.sendSuccess(() -> Component.literal(message), false),
|
||||
message -> source.sendFailure(Component.literal(message)));
|
||||
}
|
||||
|
||||
private void requestBuild(CommandSourceStack source, boolean reload) {
|
||||
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) {
|
||||
source.sendFailure(Component.literal("AstraPacks остановлен."));
|
||||
return;
|
||||
return rejected("AstraPacks остановлен.", failure);
|
||||
}
|
||||
if (!config.enabled) return rejected("AstraPacks отключён: публикация ресурспака недоступна.", failure);
|
||||
if (building) {
|
||||
source.sendFailure(Component.literal("Сборка AstraPacks уже выполняется."));
|
||||
return;
|
||||
return rejected("Сборка AstraPacks уже выполняется.", failure);
|
||||
}
|
||||
|
||||
var inputs = new BuildInputs(prepareInputs);
|
||||
building = true;
|
||||
source.sendSuccess(
|
||||
() -> Component.literal("AstraPacks: проверка и подготовка ресурспака…"), false);
|
||||
worker.execute(() -> preparePack(source, reload));
|
||||
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 void preparePack(CommandSourceStack source, boolean reload) {
|
||||
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)
|
||||
@@ -217,30 +263,52 @@ public final class PackRuntime implements AutoCloseable {
|
||||
"Изменение enabled, каталога хранения или настроек HTTP-сервера требует"
|
||||
+ " перезапуска.");
|
||||
}
|
||||
PackBuilder.Pack pack = new PackBuilder(next).build(root, RESOURCE_VERSION);
|
||||
server.execute(() -> publishPack(source, next, pack));
|
||||
inputs.prepare();
|
||||
prepared = new PackBuilder(next).prepare(root, RESOURCE_VERSION);
|
||||
var candidate = prepared;
|
||||
callbacks.execute(() -> publishPack(result, next, candidate, success, failure));
|
||||
} catch (Exception e) {
|
||||
AstraPacks.LOG.error("Pack build/publication failed; active pack retained", e);
|
||||
server.execute(() -> failBuild(source, 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 void failBuild(CommandSourceStack source, Exception error) {
|
||||
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() + " Рабочий пак сохранён.";
|
||||
source.sendFailure(Component.literal(message));
|
||||
failure.accept(message);
|
||||
}
|
||||
|
||||
private void publishPack(CommandSourceStack source, PackConfig next, PackBuilder.Pack pack) {
|
||||
building = false;
|
||||
if (closed) {
|
||||
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;
|
||||
}
|
||||
config = next;
|
||||
host.publish(pack);
|
||||
current = pack;
|
||||
|
||||
String message =
|
||||
"AstraPacks: готово, "
|
||||
+ pack.files()
|
||||
@@ -248,11 +316,57 @@ public final class PackRuntime implements AutoCloseable {
|
||||
+ pack.bytes()
|
||||
+ " байт. SHA-1: "
|
||||
+ pack.sha1();
|
||||
source.sendSuccess(() -> Component.literal(message), true);
|
||||
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) {
|
||||
for (ServerPlayer player : server.getPlayerList().getPlayers()) {
|
||||
session(player.connection).start(player.connection::send);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,8 +390,15 @@ public final class PackRuntime implements AutoCloseable {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
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();
|
||||
|
||||
Reference in New Issue
Block a user