Avoid duplicate archive scans and repeated sync marker writes
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.event.server.ServerLoadEvent;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitRunnable;
|
||||
|
||||
import java.nio.file.*;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public final class AstraPacksPlugin extends JavaPlugin implements Listener {
|
||||
private ContentSync sync;
|
||||
private ContentSync.Result result;
|
||||
private boolean started;
|
||||
private Throwable failure;
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
try {
|
||||
Path plugins = getDataFolder().toPath().toAbsolutePath().getParent();
|
||||
sync =
|
||||
new ContentSync(
|
||||
plugins.resolve("ItemsAdder/contents"), getDataFolder().toPath());
|
||||
result = sync.sync(plugins);
|
||||
getLogger()
|
||||
.info(
|
||||
"ItemsAdder content: "
|
||||
+ result.modules()
|
||||
+ " bundles, "
|
||||
+ result.written()
|
||||
+ " updated files, "
|
||||
+ result.removed()
|
||||
+ " obsolete files removed.");
|
||||
} catch (Exception e) {
|
||||
failure = e;
|
||||
getLogger().log(Level.SEVERE, "Cannot install bundled content", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
if (failure != null) {
|
||||
getServer().getPluginManager().disablePlugin(this);
|
||||
return;
|
||||
}
|
||||
getServer().getPluginManager().registerEvents(this, this);
|
||||
if (!result.buildRequired())
|
||||
getLogger().info("Shared resource pack is current; no rebuild needed.");
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void loaded(ServerLoadEvent event) {
|
||||
if (started || !result.buildRequired()) return;
|
||||
started = true;
|
||||
new BukkitRunnable() {
|
||||
int attempts, readySeconds;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if (++attempts > 120) {
|
||||
cancel();
|
||||
getLogger()
|
||||
.severe(
|
||||
"ItemsAdder did not become ready. Pack update remains pending for next restart.");
|
||||
return;
|
||||
}
|
||||
var ia = getServer().getPluginManager().getPlugin("ItemsAdder");
|
||||
if (ia == null || !ia.isEnabled()) return;
|
||||
try {
|
||||
// Use the installed ItemsAdder's public API without an early class-loader
|
||||
// dependency.
|
||||
Class<?> api =
|
||||
Class.forName(
|
||||
"dev.lone.itemsadder.api.ItemsAdder",
|
||||
true,
|
||||
ia.getClass().getClassLoader());
|
||||
if (!(boolean) api.getMethod("areItemsLoaded").invoke(null)) {
|
||||
readySeconds = 0;
|
||||
return;
|
||||
}
|
||||
// ItemsAdder exposes the item registry before its startup lock is released.
|
||||
// Wait for the registry to stay ready across subsequent scheduler ticks.
|
||||
if (++readySeconds < 5) return;
|
||||
var command = getServer().getPluginCommand("itemsadder:iazip");
|
||||
if (command == null || command.getPlugin() != ia)
|
||||
throw new IllegalStateException("ItemsAdder /iazip is unavailable");
|
||||
cancel();
|
||||
getLogger()
|
||||
.info(
|
||||
"Building the shared resource pack once for all updated plugins...");
|
||||
if (!command.execute(getServer().getConsoleSender(), "iazip", new String[0]))
|
||||
throw new IllegalStateException("ItemsAdder rejected /iazip");
|
||||
awaitPack();
|
||||
} catch (Exception e) {
|
||||
cancel();
|
||||
getLogger()
|
||||
.log(
|
||||
Level.SEVERE,
|
||||
"Pack build could not start; update remains pending",
|
||||
e);
|
||||
}
|
||||
}
|
||||
}.runTaskTimer(this, 1, 20);
|
||||
}
|
||||
|
||||
private void awaitPack() {
|
||||
Path zip =
|
||||
getDataFolder()
|
||||
.toPath()
|
||||
.toAbsolutePath()
|
||||
.getParent()
|
||||
.resolve("ItemsAdder/output/generated.zip");
|
||||
new BukkitRunnable() {
|
||||
int attempts, stable;
|
||||
long previousSize = -1, previousTime = -1;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
if (++attempts > 300) {
|
||||
cancel();
|
||||
getLogger()
|
||||
.severe(
|
||||
"Shared pack was not completed in 5 minutes. Update remains pending for next restart.");
|
||||
return;
|
||||
}
|
||||
if (!ContentSync.validPack(zip, result.fingerprint())) {
|
||||
stable = 0;
|
||||
return;
|
||||
}
|
||||
long size = Files.size(zip), time = Files.getLastModifiedTime(zip).toMillis();
|
||||
stable = size == previousSize && time == previousTime ? stable + 1 : 0;
|
||||
previousSize = size;
|
||||
previousTime = time;
|
||||
if (stable < 3) return;
|
||||
sync.confirmed(result.fingerprint());
|
||||
cancel();
|
||||
getLogger()
|
||||
.info(
|
||||
"Shared resource pack ready: "
|
||||
+ result.modules()
|
||||
+ " bundles. Delivery is managed by ItemsAdder.");
|
||||
} catch (Exception e) {
|
||||
cancel();
|
||||
getLogger()
|
||||
.log(
|
||||
Level.SEVERE,
|
||||
"Could not confirm pack build; update remains pending",
|
||||
e);
|
||||
}
|
||||
}
|
||||
}.runTaskTimerAsynchronously(this, 20, 20);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package online.astradev.packs;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.security.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.*;
|
||||
|
||||
/** Installs bundled resources while preserving unmanaged files. */
|
||||
public final class ContentSync {
|
||||
static final String PREFIX = "astra-itemsadder/";
|
||||
static final String MARKER = "assets/astrapacks/lang/en_us.json";
|
||||
private final Path contents, state;
|
||||
|
||||
public ContentSync(Path contents, Path state) {
|
||||
this.contents = contents.toAbsolutePath().normalize();
|
||||
this.state = state.toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
public record Result(
|
||||
String fingerprint, int modules, int written, int removed, boolean buildRequired) {}
|
||||
|
||||
public Result sync(Path plugins) throws IOException {
|
||||
SortedMap<String, byte[]> desired = new TreeMap<>();
|
||||
Set<String> owners = new HashSet<>();
|
||||
Set<String> folders = new HashSet<>();
|
||||
List<byte[]> itemsAdderDescriptors = new ArrayList<>();
|
||||
try (var paths = Files.list(plugins)) {
|
||||
for (Path jar :
|
||||
paths.filter(p -> p.getFileName().toString().endsWith(".jar"))
|
||||
.sorted()
|
||||
.toList()) {
|
||||
try (var zip = new ZipFile(jar.toFile())) {
|
||||
var plugin = zip.getEntry("plugin.yml");
|
||||
if (plugin != null) {
|
||||
try (var in = zip.getInputStream(plugin)) {
|
||||
byte[] bytes = in.readAllBytes();
|
||||
String yaml = new String(bytes, StandardCharsets.UTF_8);
|
||||
if (yaml.matches("(?s).*\\bname:\\s*['\"]?ItemsAdder['\"]?\\s.*"))
|
||||
itemsAdderDescriptors.add(bytes);
|
||||
}
|
||||
}
|
||||
var descriptor = zip.getEntry("astra-pack.properties");
|
||||
if (descriptor == null) continue;
|
||||
Properties info = new Properties();
|
||||
try (var in = zip.getInputStream(descriptor)) {
|
||||
info.load(in);
|
||||
}
|
||||
String owner = info.getProperty("plugin", "");
|
||||
String folder = info.getProperty("folder", "");
|
||||
if (!"1".equals(info.getProperty("schema"))
|
||||
|| !owner.matches("[A-Za-z0-9_]+")
|
||||
|| !folder.matches("[a-z0-9_]+")
|
||||
|| folder.equals("astrapacks_meta"))
|
||||
throw new IOException("Invalid astra-pack.properties in " + jar);
|
||||
if (!owners.add(owner) || !folders.add(folder))
|
||||
throw new IOException(
|
||||
"Duplicate plugin/content bundle: " + owner + " in " + jar);
|
||||
int count = 0;
|
||||
for (var entries = zip.entries(); entries.hasMoreElements(); ) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
if (entry.isDirectory() || !entry.getName().startsWith(PREFIX)) continue;
|
||||
String name = entry.getName().substring(PREFIX.length());
|
||||
safe(contents, name);
|
||||
if (!name.startsWith(folder + "/"))
|
||||
throw new IOException("Bundle writes outside its folder: " + name);
|
||||
try (var in = zip.getInputStream(entry)) {
|
||||
byte[] bytes = in.readNBytes(32 * 1024 * 1024 + 1);
|
||||
if (bytes.length > 32 * 1024 * 1024)
|
||||
throw new IOException("Oversized resource: " + name);
|
||||
if (desired.putIfAbsent(name, bytes) != null)
|
||||
throw new IOException("Duplicate resource: " + name);
|
||||
}
|
||||
count++;
|
||||
}
|
||||
if (count == 0) throw new IOException("Empty resource bundle: " + jar);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Shared client paths must have identical contents.
|
||||
Map<String, byte[]> assets = new HashMap<>();
|
||||
for (var entry : desired.entrySet()) {
|
||||
int offset = entry.getKey().indexOf("/resourcepack/assets/");
|
||||
if (offset < 0) continue;
|
||||
String asset = entry.getKey().substring(offset + "/resourcepack/".length());
|
||||
byte[] previous = assets.putIfAbsent(asset, entry.getValue());
|
||||
if (previous != null && !Arrays.equals(previous, entry.getValue()))
|
||||
throw new IOException("Conflicting client resource: " + asset);
|
||||
}
|
||||
MessageDigest digest = sha256();
|
||||
for (var entry : desired.entrySet()) {
|
||||
digest.update(entry.getKey().getBytes(StandardCharsets.UTF_8));
|
||||
digest.update((byte) 0);
|
||||
digest.update(sha256().digest(entry.getValue()));
|
||||
}
|
||||
// Rebuild after ItemsAdder upgrades or changes to its generation/hosting settings too.
|
||||
Path iaConfig = plugins.resolve("ItemsAdder/config.yml");
|
||||
if (Files.exists(iaConfig)) digest.update(Files.readAllBytes(iaConfig));
|
||||
itemsAdderDescriptors.forEach(digest::update);
|
||||
String fingerprint = HexFormat.of().formatHex(digest.digest());
|
||||
desired.put("astrapacks_meta/resourcepack/" + MARKER, marker(fingerprint));
|
||||
Properties previous = read(state.resolve("managed.properties"));
|
||||
Properties confirmed = read(state.resolve("built.properties"));
|
||||
Path output = plugins.resolve("ItemsAdder/output/generated.zip");
|
||||
boolean needsBuild =
|
||||
!fingerprint.equals(confirmed.getProperty("fingerprint"))
|
||||
|| Files.exists(state.resolve("pending"))
|
||||
|| !validPack(output, fingerprint);
|
||||
// Validate every destination before modifying any content, including stale manifest
|
||||
// entries.
|
||||
for (String name : desired.keySet()) safe(contents, name);
|
||||
for (String name : previous.stringPropertyNames()) safe(contents, name);
|
||||
int written = 0, removed = 0;
|
||||
String backup = "backups/" + System.currentTimeMillis() + "-" + UUID.randomUUID();
|
||||
Properties managed = new Properties();
|
||||
for (var entry : desired.entrySet()) {
|
||||
Path target = safe(contents, entry.getKey());
|
||||
String hash = hash(entry.getValue());
|
||||
managed.setProperty(entry.getKey(), hash);
|
||||
// ItemsAdder optimizes some source PNGs in place. Reinstall only changed JAR
|
||||
// payloads or missing files; otherwise every restart would undo its optimization.
|
||||
if (Files.isRegularFile(target)
|
||||
&& (hash.equals(previous.getProperty(entry.getKey()))
|
||||
|| hash(Files.readAllBytes(target)).equals(hash))) continue;
|
||||
if (written == 0)
|
||||
atomicWrite(state.resolve("pending"), fingerprint.getBytes(StandardCharsets.UTF_8));
|
||||
if (Files.exists(target)) backup(target, backup, entry.getKey());
|
||||
atomicWrite(target, entry.getValue());
|
||||
written++;
|
||||
}
|
||||
for (String name : previous.stringPropertyNames()) {
|
||||
if (desired.containsKey(name)) continue;
|
||||
Path target = safe(contents, name);
|
||||
if (!Files.exists(target)) continue;
|
||||
if (written == 0 && removed == 0)
|
||||
atomicWrite(state.resolve("pending"), fingerprint.getBytes(StandardCharsets.UTF_8));
|
||||
backup(target, backup, name);
|
||||
Files.delete(target);
|
||||
removed++;
|
||||
}
|
||||
store(state.resolve("managed.properties"), managed);
|
||||
needsBuild |= written > 0 || removed > 0;
|
||||
if (needsBuild && written == 0 && removed == 0)
|
||||
atomicWrite(state.resolve("pending"), fingerprint.getBytes(StandardCharsets.UTF_8));
|
||||
return new Result(fingerprint, owners.size(), written, removed, needsBuild);
|
||||
}
|
||||
|
||||
public void confirmed(String fingerprint) throws IOException {
|
||||
Properties built = new Properties();
|
||||
built.setProperty("fingerprint", fingerprint);
|
||||
store(state.resolve("built.properties"), built);
|
||||
Files.deleteIfExists(state.resolve("pending"));
|
||||
}
|
||||
|
||||
public static boolean validPack(Path path, String fingerprint) {
|
||||
if (!Files.isRegularFile(path)) return false;
|
||||
try (var zip = new ZipFile(path.toFile())) {
|
||||
var entry = zip.getEntry(MARKER);
|
||||
if (entry == null || zip.getEntry("pack.mcmeta") == null) return false;
|
||||
try (var in = zip.getInputStream(entry)) {
|
||||
String json = new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
return json.contains("\"" + fingerprint + "\"");
|
||||
}
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] marker(String fingerprint) {
|
||||
return ("{\"astrapacks.build\":\"" + fingerprint + "\"}\n")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private void backup(Path source, String backup, String name) throws IOException {
|
||||
atomicWrite(safe(state, backup + "/" + name), Files.readAllBytes(source));
|
||||
}
|
||||
|
||||
static Path safe(Path root, String name) throws IOException {
|
||||
if (name.isBlank()
|
||||
|| name.contains("\\")
|
||||
|| name.contains(":")
|
||||
|| name.startsWith("/")
|
||||
|| Arrays.stream(name.split("/", -1))
|
||||
.anyMatch(p -> p.isEmpty() || p.equals(".") || p.equals("..")))
|
||||
throw new IOException("Unsafe resource path: " + name);
|
||||
root = root.toAbsolutePath().normalize();
|
||||
Path target = root.resolve(name).normalize();
|
||||
if (!target.startsWith(root))
|
||||
throw new IOException("Resource escapes content root: " + name);
|
||||
for (Path part = target; part != null; part = part.getParent())
|
||||
if (Files.isSymbolicLink(part))
|
||||
throw new IOException("Symbolic links are not supported: " + part);
|
||||
return target;
|
||||
}
|
||||
|
||||
static void atomicWrite(Path target, byte[] bytes) throws IOException {
|
||||
Files.createDirectories(target.getParent());
|
||||
Path temp = Files.createTempFile(target.getParent(), ".astra-", ".tmp");
|
||||
try {
|
||||
Files.write(temp, bytes);
|
||||
try {
|
||||
Files.move(
|
||||
temp,
|
||||
target,
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException e) {
|
||||
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(temp);
|
||||
}
|
||||
}
|
||||
|
||||
static Properties read(Path path) throws IOException {
|
||||
Properties result = new Properties();
|
||||
if (Files.exists(path))
|
||||
try (var in = Files.newInputStream(path)) {
|
||||
result.load(in);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static void store(Path path, Properties props) throws IOException {
|
||||
var bytes = new ByteArrayOutputStream();
|
||||
props.store(bytes, "Managed by AstraPacks");
|
||||
atomicWrite(path, bytes.toByteArray());
|
||||
}
|
||||
|
||||
static MessageDigest sha256() {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
static String hash(byte[] bytes) {
|
||||
return HexFormat.of().formatHex(sha256().digest(bytes));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user