Files
AstraPacks/src/main/java/online/astradev/packs/PackBuilder.java
T

218 lines
9.0 KiB
Java
Raw Normal View History

package online.astradev.packs;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
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.util.HexFormat;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/** 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 final PackConfig config;
public PackBuilder(PackConfig config) {
this.config = config;
}
public Pack build(Path root, String resourceVersion) throws IOException {
Path contents = config.contents(root);
if (!Files.isDirectory(contents)) {
throw new IOException("Resource directory is missing: " + contents);
}
for (Path parent = contents; parent != null; parent = parent.getParent()) {
if (Files.isSymbolicLink(parent)) {
throw new IOException("Symbolic links are not supported: " + parent);
}
}
Path output = config.storage(root).resolve("output");
Files.createDirectories(output);
Path temporary = Files.createTempFile(output, "build-", ".tmp");
try {
int files = writeArchive(contents, temporary, resourceVersion);
String sha1 = sha1(temporary);
Path destination = output.resolve(sha1 + ".zip");
boolean created = !Files.exists(destination);
if (created) {
Files.move(temporary, destination, StandardCopyOption.ATOMIC_MOVE);
} 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;
} finally {
Files.deleteIfExists(temporary);
}
}
private int writeArchive(Path contents, Path target, String resourceVersion) throws IOException {
// Shared with server-side exporters (AstraPlus). A build must see one complete asset generation.
String lock = "AstraPacks:contents:" + contents.toAbsolutePath().normalize().toString().toLowerCase(java.util.Locale.ROOT);
synchronized (lock.intern()) {
return writeLockedArchive(contents, target, resourceVersion);
}
}
private int writeLockedArchive(Path contents, Path target, String resourceVersion) throws IOException {
int files = 0;
long totalBytes = 0;
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(File.separatorChar, '/');
if (!name.startsWith("assets/") && !name.equals("pack.png")) {
continue;
}
if (name.contains("\\") || name.contains(":")) {
throw new IOException("Invalid resource name: " + name);
}
if (++files > config.build.maxFiles) {
throw new IOException("Too many resources");
}
ZipEntry entry = new ZipEntry(name);
entry.setTime(0);
zip.putNextEntry(entry);
long limit = Math.min(config.build.maxFileMiB * 1024L * 1024L,
config.build.maxTotalMiB * 1024L * 1024L - totalBytes);
totalBytes += copyResource(file, zip, limit);
zip.closeEntry();
}
ZipEntry metadata = new ZipEntry("pack.mcmeta");
metadata.setTime(0);
zip.putNextEntry(metadata);
zip.write(metadata(resourceVersion));
zip.closeEntry();
}
return files + 1;
}
private static long copyResource(Path file, OutputStream output, long limit) throws IOException {
byte[] buffer = new byte[8192];
long size = 0;
try (var input = Files.newInputStream(file)) {
int read;
while ((read = input.read(buffer)) != -1) {
size += read;
if (size > limit) {
throw new IOException("Resource exceeds configured size limit: " + file);
}
output.write(buffer, 0, read);
}
}
return size;
}
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 (!sha1(path).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 {
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);
}
return info;
} catch (RuntimeException e) {
throw new IOException("Invalid resource pack manifest: " + path, e);
}
}
private static String sha1(Path file) throws IOException {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
try (var input = new DigestInputStream(Files.newInputStream(file), digest)) {
input.transferTo(OutputStream.nullOutputStream());
}
return HexFormat.of().formatHex(digest.digest());
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
}