Build shared resource folder with two-version retention and dedicated HTTP hosting

This commit is contained in:
2026-09-06 19:20:55 +03:00
parent 5b51cba772
commit f701699db8
12 changed files with 426 additions and 505 deletions
@@ -2,239 +2,185 @@ package online.astradev.packs;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.Map;
import java.util.Properties;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
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. */
/** 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) {}
private record Asset(byte[] data, String source) {}
private final PackConfig config;
private final SortedMap<String, Asset> assets = new TreeMap<>();
private long sourceBytes;
public PackBuilder(PackConfig config) {
this.config = config;
}
public Pack build(Path root, String resourceVersion) throws IOException {
assets.clear();
sourceBytes = 0;
readSources(root);
if (config.build.scanModJars) {
readModBundles(root.resolve("mods"));
Path contents = config.contents(root);
if (!Files.isDirectory(contents) || Files.isSymbolicLink(contents)) {
throw new IOException("Resource directory is missing or is a symbolic link: " + contents);
}
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)) {
readDirectory(path);
} else {
readArchive(path);
}
}
}
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 name = root.relativize(file).toString().replace('\\', '/');
// Accept a pack root or a directory containing named pack roots.
if (!isResource(name)) {
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;
}
}
try (InputStream input = Files.newInputStream(file)) {
addAsset(name, input, file.toString());
}
}
}
}
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/");
}
}
}
}
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());
}
}
}
private static boolean isResource(String name) {
return name.startsWith("assets/") || name.equals("pack.png");
}
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 = 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 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 {
Path output = config.storage(root).resolve("output");
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();
}
}
int files = writeArchive(contents, temporary, resourceVersion);
String sha1 = hash(temporary, "SHA-1");
Path destination = output.resolve(sha1 + ".zip");
if (!Files.exists(destination)) {
boolean created = !Files.exists(destination);
if (created) {
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));
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;
} finally {
Files.deleteIfExists(temporary);
}
}
public static Pack previous(Path root, PackConfig config) throws IOException {
private int writeArchive(Path contents, Path target, String resourceVersion) throws IOException {
int files = 0;
long totalBytes = 0;
byte[] buffer = new byte[8192];
try (var paths = Files.walk(contents);
var zip = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(target)))) {
for (Path file : paths.sorted().toList()) {
if (Files.isSymbolicLink(file)) {
throw new IOException("Symbolic links are not supported: " + file);
}
if (!Files.isRegularFile(file)) {
continue;
}
String name = contents.relativize(file).toString().replace('\\', '/');
if (!name.startsWith("assets/") && !name.equals("pack.png")) {
continue;
}
PackFiles.safe(contents, name);
if (++files > config.build.maxFiles) {
throw new IOException("Too many resources");
}
ZipEntry entry = new ZipEntry(name);
entry.setTime(0);
zip.putNextEntry(entry);
long fileBytes = 0;
try (var input = Files.newInputStream(file)) {
int read;
while ((read = input.read(buffer)) != -1) {
fileBytes += read;
totalBytes += read;
if (fileBytes > config.build.maxFileMiB * 1024L * 1024L) {
throw new IOException("Resource exceeds maxFileMiB: " + file);
}
if (totalBytes > config.build.maxTotalMiB * 1024L * 1024L) {
throw new IOException("Resources exceed maxTotalMiB");
}
zip.write(buffer, 0, read);
}
}
zip.closeEntry();
}
ZipEntry metadata = new ZipEntry("pack.mcmeta");
metadata.setTime(0);
zip.putNextEntry(metadata);
zip.write(metadata(resourceVersion));
zip.closeEntry();
}
return files + 1;
}
private byte[] metadata(String resourceVersion) {
var 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);
return PackConfig.JSON.toJson(metadata).getBytes(StandardCharsets.UTF_8);
}
private static void saveCurrent(Path output, Pack pack) throws IOException {
Path manifest = output.resolve("current.json");
String previous = null;
if (Files.exists(manifest)) {
JsonObject old = readManifest(manifest);
String current = old.get("sha1").getAsString();
if (!current.equals(pack.sha1())) {
previous = current;
} else if (old.has("previousSha1")) {
previous = old.get("previousSha1").getAsString();
}
}
JsonObject info = new JsonObject();
info.addProperty("sha1", pack.sha1());
info.addProperty("files", pack.files());
if (previous != null) {
info.addProperty("previousSha1", previous);
}
// Only remove generated hash-named ZIPs, never user content or unrelated files.
try (var paths = Files.list(output)) {
for (Path path : paths.toList()) {
String name = path.getFileName().toString();
if (name.matches("[a-f0-9]{40}\\.zip") && !name.equals(pack.sha1() + ".zip")
&& (previous == null || !name.equals(previous + ".zip"))
&& Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS)) {
Files.delete(path);
}
}
}
PackFiles.atomicWrite(manifest, PackConfig.JSON.toJson(info).getBytes(StandardCharsets.UTF_8));
}
public static Pack latest(Path root, PackConfig config) throws IOException {
Path output = config.storage(root).resolve("output");
JsonObject info = readManifest(output.resolve("current.json"));
String sha1 = info.get("sha1").getAsString();
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));
}
private static JsonObject readManifest(Path path) throws IOException {
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");
JsonObject info = JsonParser.parseString(Files.readString(path)).getAsJsonObject();
if (!info.get("sha1").getAsString().matches("[a-f0-9]{40}")
|| (info.has("previousSha1") && !info.get("previousSha1").getAsString().matches("[a-f0-9]{40}"))
|| info.get("files").getAsInt() < 1) {
throw new IOException("Invalid resource pack manifest: " + path);
}
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));
return info;
} catch (RuntimeException e) {
throw new IOException("Invalid previous build", e);
throw new IOException("Invalid resource pack manifest: " + path, e);
}
}
@@ -249,35 +195,4 @@ public final class PackBuilder {
throw new AssertionError(e);
}
}
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());
}
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);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
}