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,9 +1,5 @@
package online.astradev.packs;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -29,15 +25,19 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/** Deterministic, bounded build. Immutable published ZIPs remain valid during later builds. */
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/** Builds reproducible ZIPs and keeps old artifacts available to clients still downloading them. */
public final class PackBuilder {
public record Pack(Path path, String sha1, int files, long bytes) {}
private record Asset(byte[] data, String owner) {}
private record Asset(byte[] data, String source) {}
private final PackConfig config;
private final SortedMap<String, Asset> assets = new TreeMap<>();
private long total;
private long sourceBytes;
public PackBuilder(PackConfig config) {
this.config = config;
@@ -45,126 +45,107 @@ public final class PackBuilder {
public Pack build(Path root, String resourceVersion) throws IOException {
assets.clear();
total = 0;
sourceBytes = 0;
readSources(root);
if (config.build.scanModJars) {
readModBundles(root.resolve("mods"));
}
addMetadata(resourceVersion);
return writePack(config.storage(root).resolve("output"));
}
private void readSources(Path root) throws IOException {
for (String source : config.build.sources) {
Path path = root.resolve(source).toAbsolutePath().normalize();
if (!Files.exists(path)) throw new IOException("Source does not exist: " + path);
if (Files.isDirectory(path)) directory(path);
else archive(path, false);
}
if (config.build.scanModJars && Files.isDirectory(root.resolve("mods"))) {
try (var files = Files.list(root.resolve("mods"))) {
for (Path jar : files.filter(p -> p.toString().endsWith(".jar")).sorted().toList())
archive(jar, true);
if (!Files.exists(path)) {
throw new IOException("Source does not exist: " + path);
}
if (Files.isDirectory(path)) {
readDirectory(path);
} else {
readArchive(path);
}
}
JsonObject pack = new JsonObject();
// 26.2 uses major/minor resource-pack versions.
JsonElement version = JsonParser.parseString(resourceVersion);
pack.add("min_format", version);
pack.add("max_format", version.deepCopy());
pack.addProperty("description", config.build.description);
JsonObject meta = new JsonObject();
meta.add("pack", pack);
assets.put(
"pack.mcmeta",
new Asset(
PackConfig.JSON.toJson(meta).getBytes(StandardCharsets.UTF_8),
"AstraPacks"));
Path output = config.storage(root).resolve("output");
Files.createDirectories(output);
Path temp = Files.createTempFile(output, "build-", ".tmp");
try {
try (var zip =
new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temp)))) {
for (var item : assets.entrySet()) {
ZipEntry entry = new ZipEntry(item.getKey());
entry.setTime(0);
zip.putNextEntry(entry);
zip.write(item.getValue().data());
zip.closeEntry();
}
private void readDirectory(Path root) throws IOException {
if (Files.isSymbolicLink(root)) {
throw new IOException("Symlink source: " + root);
}
try (var paths = Files.walk(root)) {
for (Path file : paths.sorted().toList()) {
if (Files.isSymbolicLink(file)) {
throw new IOException("Symlink resource: " + file);
}
if (!Files.isRegularFile(file)) {
continue;
}
}
String hash = hash(temp, "SHA-1");
Path destination = output.resolve(hash + ".zip");
if (!Files.exists(destination))
Files.move(temp, destination, StandardCopyOption.ATOMIC_MOVE);
else if (!hash(destination, "SHA-1").equals(hash))
throw new IOException("Published ZIP was modified: " + destination);
PackFiles.atomicWrite(
output.resolve("current.json"),
PackConfig.JSON
.toJson(Map.of("sha1", hash, "files", assets.size()))
.getBytes(StandardCharsets.UTF_8));
return new Pack(destination, hash, assets.size(), Files.size(destination));
} finally {
Files.deleteIfExists(temp);
}
}
public static Pack previous(Path root, PackConfig config) throws IOException {
Path output = config.storage(root).resolve("output");
try {
JsonObject info =
JsonParser.parseString(Files.readString(output.resolve("current.json")))
.getAsJsonObject();
String sha1 = info.get("sha1").getAsString();
if (!sha1.matches("[a-f0-9]{40}")) throw new IOException("Invalid pack hash");
Path path = output.resolve(sha1 + ".zip");
if (!hash(path, "SHA-1").equals(sha1))
throw new IOException("Stored resource pack hash mismatch");
return new Pack(path, sha1, info.get("files").getAsInt(), Files.size(path));
} catch (RuntimeException e) {
throw new IOException("Invalid previous build", e);
}
}
private void directory(Path root) throws IOException {
if (Files.isSymbolicLink(root)) throw new IOException("Symlink source: " + root);
try (var walk = Files.walk(root)) {
for (Path p : walk.sorted().toList()) {
if (Files.isSymbolicLink(p)) throw new IOException("Symlink resource: " + p);
if (!Files.isRegularFile(p)) continue;
String name = root.relativize(p).toString().replace('\\', '/');
// A source is a pack root, or a directory of named pack roots.
String name = root.relativize(file).toString().replace('\\', '/');
// Accept a pack root or a directory containing named pack roots.
if (!isResource(name)) {
int slash = name.indexOf('/');
if (slash >= 0 && isResource(name.substring(slash + 1)))
name = name.substring(slash + 1);
else if (name.endsWith(".zip")) {
archive(p, false);
int separator = name.indexOf('/');
String nestedName = name.substring(separator + 1);
if (separator >= 0 && isResource(nestedName)) {
name = nestedName;
} else if (name.endsWith(".zip")) {
readArchive(file);
continue;
} else continue;
} else {
continue;
}
}
try (var in = Files.newInputStream(p)) {
add(name, in, p.toString());
try (InputStream input = Files.newInputStream(file)) {
addAsset(name, input, file.toString());
}
}
}
}
private void archive(Path path, boolean mod) throws IOException {
try (var zip = new ZipFile(path.toFile())) {
String prefix = "";
if (mod) {
var descriptor = zip.getEntry("astra-pack.properties");
if (descriptor == null) return;
Properties props = new Properties();
try (var in = zip.getInputStream(descriptor)) {
props.load(in);
private void readArchive(Path path) throws IOException {
try (ZipFile zip = new ZipFile(path.toFile())) {
readEntries(zip, "");
}
}
private void readModBundles(Path mods) throws IOException {
if (!Files.isDirectory(mods)) {
return;
}
try (var paths = Files.list(mods)) {
for (Path jar : paths.filter(path -> path.toString().endsWith(".jar")).sorted().toList()) {
try (ZipFile zip = new ZipFile(jar.toFile())) {
ZipEntry descriptor = zip.getEntry("astra-pack.properties");
if (descriptor == null) {
continue;
}
Properties properties = new Properties();
try (InputStream input = zip.getInputStream(descriptor)) {
properties.load(input);
}
if (!"2".equals(properties.getProperty("schema"))) {
throw new IOException("Invalid AstraPacks bundle descriptor: " + jar);
}
readEntries(zip, "astra-resourcepack/");
}
String schema = props.getProperty("schema", "");
if (schema.equals("2")) prefix = "astra-resourcepack/";
else throw new IOException("Invalid AstraPacks bundle descriptor: " + path);
}
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());
if (!isResource(name)) continue;
try (var in = zip.getInputStream(entry)) {
add(name, in, path + "!/" + entry.getName());
}
}
}
private void readEntries(ZipFile zip, String prefix) throws IOException {
var entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.isDirectory() || !entry.getName().startsWith(prefix)) {
continue;
}
String name = entry.getName().substring(prefix.length());
if (!isResource(name)) {
continue;
}
try (InputStream input = zip.getInputStream(entry)) {
addAsset(name, input, zip.getName() + "!/" + entry.getName());
}
}
}
@@ -173,29 +154,95 @@ public final class PackBuilder {
return name.startsWith("assets/") || name.equals("pack.png");
}
private void add(String name, InputStream in, String owner) throws IOException {
private void addAsset(String name, InputStream input, String source) throws IOException {
PackFiles.safe(Path.of("."), name);
int limit = config.build.maxFileMiB * 1024 * 1024;
byte[] bytes = in.readNBytes(limit + 1);
if (bytes.length > limit) throw new IOException("Resource exceeds maxFileMiB: " + owner);
total += bytes.length;
if (total > config.build.maxTotalMiB * 1024L * 1024L)
byte[] bytes = input.readNBytes(limit + 1);
if (bytes.length > limit) {
throw new IOException("Resource exceeds maxFileMiB: " + source);
}
sourceBytes += bytes.length;
if (sourceBytes > config.build.maxTotalMiB * 1024L * 1024L) {
throw new IOException("Sources exceed maxTotalMiB");
Asset old = assets.get(name);
if (old != null
&& !Arrays.equals(bytes, old.data())
&& config.build.conflictPolicy.equals("error"))
throw new IOException(
"Conflicting resource " + name + " from " + old.owner() + " and " + owner);
assets.put(name, new Asset(bytes, owner));
if (assets.size() > config.build.maxFiles) throw new IOException("Too many resources");
}
Asset previous = assets.get(name);
if (previous != null && config.build.conflictPolicy.equals("error")
&& !Arrays.equals(bytes, previous.data())) {
throw new IOException("Conflicting resource " + name + " from " + previous.source() + " and " + source);
}
assets.put(name, new Asset(bytes, source));
if (assets.size() > config.build.maxFiles) {
throw new IOException("Too many resources");
}
}
private void addMetadata(String resourceVersion) {
JsonElement version = JsonParser.parseString(resourceVersion);
JsonObject pack = new JsonObject();
pack.add("min_format", version);
pack.add("max_format", version.deepCopy());
pack.addProperty("description", config.build.description);
JsonObject metadata = new JsonObject();
metadata.add("pack", pack);
byte[] bytes = PackConfig.JSON.toJson(metadata).getBytes(StandardCharsets.UTF_8);
assets.put("pack.mcmeta", new Asset(bytes, "AstraPacks"));
}
private Pack writePack(Path output) throws IOException {
Files.createDirectories(output);
Path temporary = Files.createTempFile(output, "build-", ".tmp");
try {
try (var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(temporary)))) {
for (var asset : assets.entrySet()) {
ZipEntry entry = new ZipEntry(asset.getKey());
entry.setTime(0);
zip.putNextEntry(entry);
zip.write(asset.getValue().data());
zip.closeEntry();
}
}
String sha1 = hash(temporary, "SHA-1");
Path destination = output.resolve(sha1 + ".zip");
if (!Files.exists(destination)) {
Files.move(temporary, destination, StandardCopyOption.ATOMIC_MOVE);
} else if (!hash(destination, "SHA-1").equals(sha1)) {
throw new IOException("Published ZIP was modified: " + destination);
}
String manifest = PackConfig.JSON.toJson(Map.of("sha1", sha1, "files", assets.size()));
PackFiles.atomicWrite(output.resolve("current.json"), manifest.getBytes(StandardCharsets.UTF_8));
return new Pack(destination, sha1, assets.size(), Files.size(destination));
} finally {
Files.deleteIfExists(temporary);
}
}
public static Pack previous(Path root, PackConfig config) throws IOException {
Path output = config.storage(root).resolve("output");
try {
String manifest = Files.readString(output.resolve("current.json"));
JsonObject info = JsonParser.parseString(manifest).getAsJsonObject();
String sha1 = info.get("sha1").getAsString();
if (!sha1.matches("[a-f0-9]{40}")) {
throw new IOException("Invalid pack hash");
}
Path path = output.resolve(sha1 + ".zip");
if (!hash(path, "SHA-1").equals(sha1)) {
throw new IOException("Stored resource pack hash mismatch");
}
return new Pack(path, sha1, info.get("files").getAsInt(), Files.size(path));
} catch (RuntimeException e) {
throw new IOException("Invalid previous build", e);
}
}
public static String hash(Path file, String algorithm) throws IOException {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
try (var in = new DigestInputStream(Files.newInputStream(file), digest)) {
in.transferTo(OutputStream.nullOutputStream());
try (var input = new DigestInputStream(Files.newInputStream(file), digest)) {
input.transferTo(OutputStream.nullOutputStream());
}
return HexFormat.of().formatHex(digest.digest());
} catch (NoSuchAlgorithmException e) {
@@ -203,34 +250,29 @@ public final class PackBuilder {
}
}
static void verifyExternal(PackConfig config, PackBuilder.Pack pack) throws IOException {
if (!config.hosting.mode.equals("no_host") || !config.delivery.sendOnJoin) return;
try (HttpClient client =
HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NORMAL)
.build()) {
HttpRequest request =
HttpRequest.newBuilder(PackConfig.validateUrl(config.hosting.externalUrl))
.timeout(Duration.ofSeconds(30))
.GET()
.build();
// A bounded subscriber prevents an external host from consuming arbitrary memory/disk.
HttpResponse<byte[]> response =
client.send(
request,
HttpResponse.BodyHandlers.limiting(
HttpResponse.BodyHandlers.ofByteArray(), pack.bytes()));
if (response.statusCode() != 200)
static void verifyExternal(PackConfig config, Pack pack) throws IOException {
if (!config.hosting.mode.equals("no_host") || !config.delivery.sendOnJoin) {
return;
}
try (HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.followRedirects(HttpClient.Redirect.NORMAL)
.build()) {
HttpRequest request = HttpRequest.newBuilder(PackConfig.validateUrl(config.hosting.externalUrl))
.timeout(Duration.ofSeconds(30))
.GET()
.build();
var bodyHandler = HttpResponse.BodyHandlers.limiting(HttpResponse.BodyHandlers.ofByteArray(), pack.bytes());
HttpResponse<byte[]> response = client.send(request, bodyHandler);
if (response.statusCode() != 200) {
throw new IOException("External pack HTTP " + response.statusCode());
String hash =
HexFormat.of()
.formatHex(MessageDigest.getInstance("SHA-1").digest(response.body()));
if (!hash.equals(pack.sha1()))
throw new IOException(
"External ZIP differs from built ZIP. Upload "
+ pack.path()
+ ", then /astrapacks publish");
}
byte[] digest = MessageDigest.getInstance("SHA-1").digest(response.body());
if (!HexFormat.of().formatHex(digest).equals(pack.sha1())) {
throw new IOException("External ZIP differs from built ZIP. Upload " + pack.path()
+ ", then /astrapacks publish");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(e);