| 1 | package net.minecraft.data;
|
| 2 |
|
| 3 | import com.google.common.collect.ImmutableMap;
|
| 4 | import com.google.common.collect.ImmutableMap.Builder;
|
| 5 | import com.google.common.hash.HashCode;
|
| 6 | import com.google.common.hash.Hashing;
|
| 7 | import com.mojang.logging.LogUtils;
|
| 8 | import java.io.BufferedReader;
|
| 9 | import java.io.BufferedWriter;
|
| 10 | import java.io.IOException;
|
| 11 | import java.nio.charset.StandardCharsets;
|
| 12 | import java.nio.file.FileVisitResult;
|
| 13 | import java.nio.file.Files;
|
| 14 | import java.nio.file.Path;
|
| 15 | import java.nio.file.SimpleFileVisitor;
|
| 16 | import java.nio.file.attribute.BasicFileAttributes;
|
| 17 | import java.time.ZonedDateTime;
|
| 18 | import java.time.format.DateTimeFormatter;
|
| 19 | import java.util.Collection;
|
| 20 | import java.util.HashMap;
|
| 21 | import java.util.HashSet;
|
| 22 | import java.util.Map;
|
| 23 | import java.util.Objects;
|
| 24 | import java.util.Set;
|
| 25 | import java.util.Map.Entry;
|
| 26 | import java.util.concurrent.CompletableFuture;
|
| 27 | import java.util.concurrent.ConcurrentHashMap;
|
| 28 | import java.util.concurrent.ConcurrentMap;
|
| 29 | import java.util.concurrent.atomic.AtomicInteger;
|
| 30 | import net.minecraft.WorldVersion;
|
| 31 | import org.apache.commons.lang3.mutable.MutableInt;
|
| 32 | import org.jspecify.annotations.Nullable;
|
| 33 | import org.slf4j.Logger;
|
| 34 |
|
| 35 | public class HashCache {
|
| 36 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 37 | private static final String HEADER_MARKER = "// ";
|
| 38 | private final Path rootDir;
|
| 39 | private final Path cacheDir;
|
| 40 | private final String versionId;
|
| 41 | private final Map<String, HashCache.ProviderCache> caches;
|
| 42 | private final Set<String> cachesToWrite = new HashSet<>();
|
| 43 | private final Set<Path> cachePaths = new HashSet<>();
|
| 44 | private final int initialCount;
|
| 45 | private int writes;
|
| 46 |
|
| 47 | private Path getProviderCachePath(final String provider) {
|
| 48 | return this.cacheDir.resolve(Hashing.sha1().hashString(provider, StandardCharsets.UTF_8).toString());
|
| 49 | }
|
| 50 |
|
| 51 | public HashCache(final Path rootDir, final Collection<String> providerIds, final WorldVersion version) throws IOException {
|
| 52 | this.versionId = version.id();
|
| 53 | this.rootDir = rootDir;
|
| 54 | this.cacheDir = rootDir.resolve(".cache");
|
| 55 | Files.createDirectories(this.cacheDir);
|
| 56 | Map<String, HashCache.ProviderCache> loadedCaches = new HashMap<>();
|
| 57 | int initialCount = 0;
|
| 58 |
|
| 59 | for (String providerId : providerIds) {
|
| 60 | Path providerCachePath = this.getProviderCachePath(providerId);
|
| 61 | this.cachePaths.add(providerCachePath);
|
| 62 | HashCache.ProviderCache providerCache = readCache(rootDir, providerCachePath);
|
| 63 | loadedCaches.put(providerId, providerCache);
|
| 64 | initialCount += providerCache.count();
|
| 65 | }
|
| 66 |
|
| 67 | this.caches = loadedCaches;
|
| 68 | this.initialCount = initialCount;
|
| 69 | }
|
| 70 |
|
| 71 | private static HashCache.ProviderCache readCache(final Path rootDir, final Path providerCachePath) {
|
| 72 | if (Files.isReadable(providerCachePath)) {
|
| 73 | try {
|
| 74 | return HashCache.ProviderCache.load(rootDir, providerCachePath);
|
| 75 | } catch (Exception e) {
|
| 76 | LOGGER.warn("Failed to parse cache {}, discarding", providerCachePath, e);
|
| 77 | }
|
| 78 | }
|
| 79 |
|
| 80 | return new HashCache.ProviderCache("unknown", ImmutableMap.of());
|
| 81 | }
|
| 82 |
|
| 83 | public boolean shouldRunInThisVersion(final String providerId) {
|
| 84 | HashCache.ProviderCache result = this.caches.get(providerId);
|
| 85 | return result == null || !result.version.equals(this.versionId);
|
| 86 | }
|
| 87 |
|
| 88 | public CompletableFuture<HashCache.UpdateResult> generateUpdate(final String providerId, final HashCache.UpdateFunction function) {
|
| 89 | HashCache.ProviderCache existingCache = this.caches.get(providerId);
|
| 90 | if (existingCache == null) {
|
| 91 | throw new IllegalStateException("Provider not registered: " + providerId);
|
| 92 | }
|
| 93 |
|
| 94 | HashCache.CacheUpdater output = new HashCache.CacheUpdater(providerId, this.versionId, existingCache);
|
| 95 | return function.update(output).thenApply(unused -> output.close());
|
| 96 | }
|
| 97 |
|
| 98 | public void applyUpdate(final HashCache.UpdateResult result) {
|
| 99 | this.caches.put(result.providerId(), result.cache());
|
| 100 | this.cachesToWrite.add(result.providerId());
|
| 101 | this.writes = this.writes + result.writes();
|
| 102 | }
|
| 103 |
|
| 104 | public void purgeStaleAndWrite() throws IOException {
|
| 105 | final Set<Path> allowedFiles = new HashSet<>();
|
| 106 | this.caches.forEach((providerId, cache) -> {
|
| 107 | if (this.cachesToWrite.contains(providerId)) {
|
| 108 | Path cachePath = this.getProviderCachePath(providerId);
|
| 109 | cache.save(this.rootDir, cachePath, DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(ZonedDateTime.now()) + "\t" + providerId);
|
| 110 | }
|
| 111 |
|
| 112 | allowedFiles.addAll(cache.data().keySet());
|
| 113 | });
|
| 114 | final MutableInt found = new MutableInt();
|
| 115 | final MutableInt removed = new MutableInt();
|
| 116 | Files.walkFileTree(this.rootDir, new SimpleFileVisitor<Path>() {
|
| 117 | public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) {
|
| 118 | if (HashCache.this.cachePaths.contains(file)) {
|
| 119 | return FileVisitResult.CONTINUE;
|
| 120 | }
|
| 121 |
|
| 122 | found.increment();
|
| 123 | if (allowedFiles.contains(file)) {
|
| 124 | return FileVisitResult.CONTINUE;
|
| 125 | }
|
| 126 |
|
| 127 | try {
|
| 128 | Files.delete(file);
|
| 129 | } catch (IOException e) {
|
| 130 | HashCache.LOGGER.warn("Failed to delete file {}", file, e);
|
| 131 | }
|
| 132 |
|
| 133 | removed.increment();
|
| 134 | return FileVisitResult.CONTINUE;
|
| 135 | }
|
| 136 | });
|
| 137 | LOGGER.info(
|
| 138 | "Caching: total files: {}, old count: {}, new count: {}, removed stale: {}, written: {}",
|
| 139 | found,
|
| 140 | this.initialCount,
|
| 141 | allowedFiles.size(),
|
| 142 | removed,
|
| 143 | this.writes
|
| 144 | );
|
| 145 | }
|
| 146 |
|
| 147 | private static class CacheUpdater implements CachedOutput {
|
| 148 | private final String provider;
|
| 149 | private final HashCache.ProviderCache oldCache;
|
| 150 | private final HashCache.ProviderCacheBuilder newCache;
|
| 151 | private final AtomicInteger writes = new AtomicInteger();
|
| 152 | private volatile boolean closed;
|
| 153 |
|
| 154 | private CacheUpdater(final String provider, final String newVersionId, final HashCache.ProviderCache oldCache) {
|
| 155 | this.provider = provider;
|
| 156 | this.oldCache = oldCache;
|
| 157 | this.newCache = new HashCache.ProviderCacheBuilder(newVersionId);
|
| 158 | }
|
| 159 |
|
| 160 | private boolean shouldWrite(final Path path, final HashCode hash) {
|
| 161 | return !Objects.equals(this.oldCache.get(path), hash) || !Files.exists(path);
|
| 162 | }
|
| 163 |
|
| 164 | @Override
|
| 165 | public void writeIfNeeded(final Path path, final byte[] input, final HashCode hash) throws IOException {
|
| 166 | if (this.closed) {
|
| 167 | throw new IllegalStateException("Cannot write to cache as it has already been closed");
|
| 168 | }
|
| 169 |
|
| 170 | if (this.shouldWrite(path, hash)) {
|
| 171 | this.writes.incrementAndGet();
|
| 172 | Files.createDirectories(path.getParent());
|
| 173 | Files.write(path, input);
|
| 174 | }
|
| 175 |
|
| 176 | this.newCache.put(path, hash);
|
| 177 | }
|
| 178 |
|
| 179 | public HashCache.UpdateResult close() {
|
| 180 | this.closed = true;
|
| 181 | return new HashCache.UpdateResult(this.provider, this.newCache.build(), this.writes.get());
|
| 182 | }
|
| 183 | }
|
| 184 |
|
| 185 | private record ProviderCache(String version, ImmutableMap<Path, HashCode> data) {
|
| 186 | public @Nullable HashCode get(final Path path) {
|
| 187 | return this.data.get(path);
|
| 188 | }
|
| 189 |
|
| 190 | public int count() {
|
| 191 | return this.data.size();
|
| 192 | }
|
| 193 |
|
| 194 | public static HashCache.ProviderCache load(final Path rootDir, final Path cacheFile) throws IOException {
|
| 195 | try (BufferedReader reader = Files.newBufferedReader(cacheFile, StandardCharsets.UTF_8)) {
|
| 196 | String header = reader.readLine();
|
| 197 | if (!header.startsWith("// ")) {
|
| 198 | throw new IllegalStateException("Missing cache file header");
|
| 199 | }
|
| 200 |
|
| 201 | String[] headerFields = header.substring("// ".length()).split("\t", 2);
|
| 202 | String savedVersionId = headerFields[0];
|
| 203 | Builder<Path, HashCode> result = ImmutableMap.builder();
|
| 204 | reader.lines().forEach(s -> {
|
| 205 | int i = s.indexOf(32);
|
| 206 | result.put(rootDir.resolve(s.substring(i + 1)), HashCode.fromString(s.substring(0, i)));
|
| 207 | });
|
| 208 | return new HashCache.ProviderCache(savedVersionId, result.build());
|
| 209 | }
|
| 210 | }
|
| 211 |
|
| 212 | public void save(final Path rootDir, final Path cacheFile, final String extraHeaderInfo) {
|
| 213 | try (BufferedWriter output = Files.newBufferedWriter(cacheFile, StandardCharsets.UTF_8)) {
|
| 214 | output.write("// ");
|
| 215 | output.write(this.version);
|
| 216 | output.write(9);
|
| 217 | output.write(extraHeaderInfo);
|
| 218 | output.newLine();
|
| 219 |
|
| 220 | for (Entry<Path, HashCode> e : this.data.entrySet()) {
|
| 221 | output.write(e.getValue().toString());
|
| 222 | output.write(32);
|
| 223 | output.write(rootDir.relativize(e.getKey()).toString());
|
| 224 | output.newLine();
|
| 225 | }
|
| 226 | } catch (IOException e) {
|
| 227 | HashCache.LOGGER.warn("Unable write cachefile {}", cacheFile, e);
|
| 228 | }
|
| 229 | }
|
| 230 | }
|
| 231 |
|
| 232 | private record ProviderCacheBuilder(String version, ConcurrentMap<Path, HashCode> data) {
|
| 233 | public ProviderCacheBuilder(final String version) {
|
| 234 | this(version, new ConcurrentHashMap<>());
|
| 235 | }
|
| 236 |
|
| 237 | public void put(final Path path, final HashCode hash) {
|
| 238 | this.data.put(path, hash);
|
| 239 | }
|
| 240 |
|
| 241 | public HashCache.ProviderCache build() {
|
| 242 | return new HashCache.ProviderCache(this.version, ImmutableMap.copyOf(this.data));
|
| 243 | }
|
| 244 | }
|
| 245 |
|
| 246 | @FunctionalInterface
|
| 247 | public interface UpdateFunction {
|
| 248 | CompletableFuture<?> update(CachedOutput output);
|
| 249 | }
|
| 250 |
|
| 251 | public record UpdateResult(String providerId, HashCache.ProviderCache cache, int writes) {
|
| 252 | }
|
| 253 | }
|
| 254 |
|