Fix resource lookup concurrency
This commit is contained in:
@@ -1,14 +1,17 @@
|
||||
package com.ccr4ft3r.lightspeed.cache;
|
||||
|
||||
import com.ccr4ft3r.lightspeed.compat.FusionPackCompat;
|
||||
import com.ccr4ft3r.lightspeed.interfaces.ICache;
|
||||
import com.ccr4ft3r.lightspeed.util.CacheUtil;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.common.collect.Sets;
|
||||
import com.mojang.logging.LogUtils;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.packs.FilePackResources;
|
||||
import net.minecraft.server.packs.PackResources;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.resources.IoSupplier;
|
||||
import net.minecraftforge.resource.PathPackResources;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.io.File;
|
||||
@@ -48,6 +51,7 @@ public class GlobalCache {
|
||||
private static final Set<ICache> CACHES = Sets.newConcurrentHashSet();
|
||||
public static final Map<String, Map<String, Boolean>> PERSISTED_EXISTENCES_BY_MOD = Maps.newConcurrentMap();
|
||||
public static final Map<String, Map<PackType, Set<String>>> PERSISTED_NAMESPACES_BY_MOD = Maps.newConcurrentMap();
|
||||
public static final Map<String, Map<PackType, Map<String, List<String>>>> PERSISTED_RESOURCE_LISTS_BY_MOD = Maps.newConcurrentMap();
|
||||
public static final int WORKER_COUNT = getWorkerCount();
|
||||
public static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(WORKER_COUNT, runnable -> {
|
||||
Thread thread = new Thread(runnable, "Lightspeed-" + THREAD_ID.incrementAndGet());
|
||||
@@ -63,7 +67,8 @@ public class GlobalCache {
|
||||
if (PERSISTED_CACHE_LOAD_STARTED.compareAndSet(false, true)) {
|
||||
persistedCacheLoad = CompletableFuture.allOf(
|
||||
loadPersistedCaches(HAS_RESOURCE_CACHE_DIR, PERSISTED_EXISTENCES_BY_MOD),
|
||||
loadPersistedCaches(NAMESPACE_CACHE_DIR, PERSISTED_NAMESPACES_BY_MOD)
|
||||
loadPersistedCaches(NAMESPACE_CACHE_DIR, PERSISTED_NAMESPACES_BY_MOD),
|
||||
loadPersistedCaches(RESOURCE_LIST_CACHE_DIR, PERSISTED_RESOURCE_LISTS_BY_MOD)
|
||||
).exceptionally(throwable -> {
|
||||
LOGGER.error("Lightspeed failed to load persisted caches", throwable);
|
||||
return null;
|
||||
@@ -99,8 +104,8 @@ public class GlobalCache {
|
||||
if (packs.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (packs.size() == 1) {
|
||||
return packs.get(0).getResource(type, location);
|
||||
if (packs.size() == 1 || !shouldParallelizeResourcePackLookup || packs.stream().anyMatch(pack -> !isSafeForParallelLookup(pack))) {
|
||||
return findFirstResourceSequential(packs, type, location);
|
||||
}
|
||||
|
||||
List<CompletableFuture<IoSupplier<InputStream>>> futures = new ArrayList<>(packs.size());
|
||||
@@ -136,6 +141,7 @@ public class GlobalCache {
|
||||
List<CompletableFuture<Void>> tasks = new ArrayList<>();
|
||||
CacheUtil.getCacheFiles(HAS_RESOURCE_CACHE_DIR).forEach(file -> tasks.add(deleteAsync(file)));
|
||||
CacheUtil.getCacheFiles(NAMESPACE_CACHE_DIR).forEach(file -> tasks.add(deleteAsync(file)));
|
||||
CacheUtil.getCacheFiles(RESOURCE_LIST_CACHE_DIR).forEach(file -> tasks.add(deleteAsync(file)));
|
||||
CACHES.forEach(cache -> tasks.add(executeLogged(cache.getClass().getName(), cache::lightspeed$persistAndClearCache)));
|
||||
|
||||
CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0])).join();
|
||||
@@ -144,6 +150,7 @@ public class GlobalCache {
|
||||
CACHES.clear();
|
||||
PERSISTED_EXISTENCES_BY_MOD.clear();
|
||||
PERSISTED_NAMESPACES_BY_MOD.clear();
|
||||
PERSISTED_RESOURCE_LISTS_BY_MOD.clear();
|
||||
}
|
||||
|
||||
private static int getWorkerCount() {
|
||||
@@ -182,4 +189,11 @@ public class GlobalCache {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isSafeForParallelLookup(PackResources packResources) {
|
||||
Class<?> packClass = packResources.getClass();
|
||||
boolean forgeModPathPack = packResources instanceof PathPackResources
|
||||
&& (packClass == PathPackResources.class || packClass.getName().startsWith("net.minecraftforge.resource.ResourcePackLoader$"));
|
||||
return (forgeModPathPack || packClass == FilePackResources.class) && !FusionPackCompat.hasOverrides(packResources);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,10 +27,10 @@ public final class LightspeedConfig {
|
||||
private Common(ForgeConfigSpec.Builder builder) {
|
||||
builder.push("startup");
|
||||
asyncPreloadPacks = builder
|
||||
.comment("Preload Forge path resource packs on Lightspeed worker threads during startup.")
|
||||
.comment("Preload Forge path resource pack indexes on Lightspeed worker threads during startup.")
|
||||
.define("asyncPreloadPacks", true);
|
||||
parallelResourceLookup = builder
|
||||
.comment("Query candidate resource packs concurrently while preserving pack priority order for the selected result.")
|
||||
.comment("Query safe resource-pack segments concurrently while preserving vanilla priority and filter order.")
|
||||
.define("parallelResourceLookup", true);
|
||||
builder.pop();
|
||||
|
||||
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package com.ccr4ft3r.lightspeed.mixin.resources;
|
||||
|
||||
import com.ccr4ft3r.lightspeed.cache.GlobalCache;
|
||||
import com.ccr4ft3r.lightspeed.compat.FusionPackCompat;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.packs.FilePackResources;
|
||||
import net.minecraft.server.packs.PackResources;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.resources.FallbackResourceManager;
|
||||
import net.minecraft.server.packs.resources.IoSupplier;
|
||||
import net.minecraft.server.packs.resources.Resource;
|
||||
import net.minecraft.server.packs.resources.ResourceMetadata;
|
||||
import net.minecraftforge.resource.PathPackResources;
|
||||
import org.slf4j.Logger;
|
||||
import org.spongepowered.asm.mixin.Final;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Shadow;
|
||||
import org.spongepowered.asm.mixin.Unique;
|
||||
import org.spongepowered.asm.mixin.gen.Invoker;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
@Mixin(FallbackResourceManager.class)
|
||||
public abstract class FallbackResourceManagerMixin {
|
||||
@Shadow @Final private static Logger LOGGER;
|
||||
@Shadow @Final public List<?> fallbacks;
|
||||
@Shadow @Final private PackType type;
|
||||
|
||||
@Invoker("createStackMetadataFinder")
|
||||
protected abstract IoSupplier<ResourceMetadata> lightspeed$createStackMetadataFinder(ResourceLocation location, int index);
|
||||
|
||||
@Invoker("createResource")
|
||||
private static Resource lightspeed$createResource(PackResources pack, ResourceLocation location,
|
||||
IoSupplier<InputStream> resource,
|
||||
IoSupplier<ResourceMetadata> metadata) {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
@Inject(method = "getResource", at = @At("HEAD"), cancellable = true)
|
||||
private void getResourceHeadInjected(ResourceLocation location, CallbackInfoReturnable<Optional<Resource>> cir) {
|
||||
if (!GlobalCache.isEnabled || !GlobalCache.shouldParallelizeResourcePackLookup || this.fallbacks.size() <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<IndexedPack> safeSegment = new ArrayList<>();
|
||||
for (int i = this.fallbacks.size() - 1; i >= 0; i--) {
|
||||
FallbackResourceManagerPackEntryAccessor entry = (FallbackResourceManagerPackEntryAccessor) this.fallbacks.get(i);
|
||||
PackResources packResources = entry.lightspeed$resources();
|
||||
|
||||
if (packResources != null && entry.lightspeed$filter() == null && lightspeed$isSafeForParallelLookup(packResources)) {
|
||||
safeSegment.add(new IndexedPack(i, packResources));
|
||||
continue;
|
||||
}
|
||||
|
||||
Optional<Resource> resource = lightspeed$searchSafeSegment(safeSegment, location);
|
||||
if (resource != null) {
|
||||
cir.setReturnValue(resource);
|
||||
return;
|
||||
}
|
||||
safeSegment.clear();
|
||||
|
||||
if (packResources != null) {
|
||||
IoSupplier<InputStream> supplier = packResources.getResource(this.type, location);
|
||||
if (supplier != null) {
|
||||
cir.setReturnValue(Optional.of(lightspeed$createResource(
|
||||
packResources, location, supplier, lightspeed$createStackMetadataFinder(location, i))));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (entry.lightspeed$isFiltered(location)) {
|
||||
LOGGER.warn("Resource {} not found, but was filtered by pack {}", location, entry.lightspeed$name());
|
||||
cir.setReturnValue(Optional.empty());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Optional<Resource> resource = lightspeed$searchSafeSegment(safeSegment, location);
|
||||
cir.setReturnValue(resource == null ? Optional.empty() : resource);
|
||||
}
|
||||
|
||||
@Unique
|
||||
private Optional<Resource> lightspeed$searchSafeSegment(List<IndexedPack> segment, ResourceLocation location) {
|
||||
if (segment.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (segment.size() == 1) {
|
||||
IndexedPack indexedPack = segment.get(0);
|
||||
IoSupplier<InputStream> supplier = indexedPack.pack().getResource(this.type, location);
|
||||
return supplier == null ? null : Optional.of(lightspeed$createResource(indexedPack.pack(), location,
|
||||
supplier, lightspeed$createStackMetadataFinder(location, indexedPack.index())));
|
||||
}
|
||||
|
||||
List<CompletableFuture<IoSupplier<InputStream>>> futures = new ArrayList<>(segment.size());
|
||||
try {
|
||||
for (IndexedPack indexedPack : segment) {
|
||||
futures.add(CompletableFuture.supplyAsync(() -> indexedPack.pack().getResource(this.type, location), GlobalCache.EXECUTOR));
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
LOGGER.warn("Lightspeed parallel resource lookup rejected for {}; falling back to vanilla order", location, e);
|
||||
return lightspeed$searchSafeSegmentSequential(segment, location);
|
||||
}
|
||||
|
||||
for (int i = 0; i < segment.size(); i++) {
|
||||
IndexedPack indexedPack = segment.get(i);
|
||||
try {
|
||||
IoSupplier<InputStream> supplier = futures.get(i).get();
|
||||
if (supplier != null) {
|
||||
return Optional.of(lightspeed$createResource(indexedPack.pack(), location,
|
||||
supplier, lightspeed$createStackMetadataFinder(location, indexedPack.index())));
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return lightspeed$searchSafeSegmentSequential(segment, location);
|
||||
} catch (ExecutionException e) {
|
||||
LOGGER.warn("Lightspeed parallel resource lookup failed for {} in {}", location, indexedPack.pack().packId(), e);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Unique
|
||||
private Optional<Resource> lightspeed$searchSafeSegmentSequential(List<IndexedPack> segment, ResourceLocation location) {
|
||||
for (IndexedPack indexedPack : segment) {
|
||||
IoSupplier<InputStream> supplier = indexedPack.pack().getResource(this.type, location);
|
||||
if (supplier != null) {
|
||||
return Optional.of(lightspeed$createResource(indexedPack.pack(), location,
|
||||
supplier, lightspeed$createStackMetadataFinder(location, indexedPack.index())));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Unique
|
||||
private static boolean lightspeed$isSafeForParallelLookup(PackResources packResources) {
|
||||
Class<?> packClass = packResources.getClass();
|
||||
boolean forgeModPathPack = packResources instanceof PathPackResources
|
||||
&& (packClass == PathPackResources.class || packClass.getName().startsWith("net.minecraftforge.resource.ResourcePackLoader$"));
|
||||
return (forgeModPathPack || packClass == FilePackResources.class) && !FusionPackCompat.hasOverrides(packResources);
|
||||
}
|
||||
|
||||
@Unique
|
||||
private record IndexedPack(int index, PackResources pack) {
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.ccr4ft3r.lightspeed.mixin.resources;
|
||||
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import net.minecraft.server.packs.PackResources;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.gen.Invoker;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
@Mixin(targets = "net.minecraft.server.packs.resources.FallbackResourceManager$PackEntry")
|
||||
public interface FallbackResourceManagerPackEntryAccessor {
|
||||
@Invoker("name")
|
||||
String lightspeed$name();
|
||||
|
||||
@Invoker("resources")
|
||||
PackResources lightspeed$resources();
|
||||
|
||||
@Invoker("filter")
|
||||
Predicate<ResourceLocation> lightspeed$filter();
|
||||
|
||||
@Invoker("isFiltered")
|
||||
boolean lightspeed$isFiltered(ResourceLocation location);
|
||||
}
|
||||
@@ -50,6 +50,9 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
|
||||
@Unique
|
||||
private Map<PackType, Map<String, List<Path>>> lightspeed$filePathsByRootByPackType;
|
||||
|
||||
@Unique
|
||||
private Map<PackType, Map<String, List<String>>> lightspeed$relativeFilePathsByPackType;
|
||||
|
||||
|
||||
@Unique
|
||||
private IModFile lightspeed$modFile;
|
||||
@@ -183,11 +186,13 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
|
||||
if (lightspeed$modFile != null) {
|
||||
CacheUtil.persist(lightspeed$getExistenceByResource(), new File(HAS_RESOURCE_CACHE_DIR.getPath(), lightspeed$id + ".ser"));
|
||||
CacheUtil.persist(lightspeed$namespaces(), new File(NAMESPACE_CACHE_DIR.getPath(), lightspeed$id + ".ser"));
|
||||
CacheUtil.persist(lightspeed$relativeFilePaths(), new File(RESOURCE_LIST_CACHE_DIR.getPath(), lightspeed$id + ".ser"));
|
||||
}
|
||||
lightspeed$getExistenceByResource().clear();
|
||||
lightspeed$resolvedPaths().clear();
|
||||
lightspeed$namespaces().clear();
|
||||
lightspeed$filePathsByRoot().clear();
|
||||
lightspeed$relativeFilePaths().clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -200,6 +205,8 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
|
||||
lightspeed$id, i -> Maps.newConcurrentMap()));
|
||||
lightspeed$namespaces().putAll(GlobalCache.PERSISTED_NAMESPACES_BY_MOD.computeIfAbsent(
|
||||
lightspeed$id, i -> Maps.newConcurrentMap()));
|
||||
lightspeed$relativeFilePaths().putAll(GlobalCache.PERSISTED_RESOURCE_LISTS_BY_MOD.computeIfAbsent(
|
||||
lightspeed$id, i -> Maps.newConcurrentMap()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -209,7 +216,7 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
|
||||
}
|
||||
|
||||
for (PackType packType : PackType.values()) {
|
||||
GlobalCache.executeLogged("preload " + lightspeed$id + " " + packType, () -> {
|
||||
GlobalCache.executeLogged("preload namespaces " + lightspeed$id + " " + packType, () -> {
|
||||
Set<String> namespaces = lightspeed$getCachedNamespaces(packType);
|
||||
if (namespaces == null) {
|
||||
namespaces = lightspeed$scanNamespaces(packType);
|
||||
@@ -217,8 +224,10 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
|
||||
}
|
||||
|
||||
for (String namespace : namespaces) {
|
||||
Path root = resolve(packType.getDirectory(), namespace).toAbsolutePath();
|
||||
lightspeed$getFilePaths(packType, namespace, root);
|
||||
GlobalCache.executeLogged("preload " + lightspeed$id + " " + packType + " " + namespace, () -> {
|
||||
Path root = resolve(packType.getDirectory(), namespace).toAbsolutePath();
|
||||
lightspeed$getFilePaths(packType, namespace, root);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -244,7 +253,17 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
|
||||
|
||||
@Unique
|
||||
public List<Path> lightspeed$getFilePaths(PackType packType, String resourceNamespace, Path root) {
|
||||
return lightspeed$getFilePathsMap(packType).computeIfAbsent(resourceNamespace, ignored -> lightspeed$scanFilePaths(root));
|
||||
return lightspeed$getFilePathsMap(packType).computeIfAbsent(resourceNamespace, ignored -> {
|
||||
List<String> cachedRelativePaths = lightspeed$getRelativeFilePathsMap(packType).get(resourceNamespace);
|
||||
if (cachedRelativePaths != null) {
|
||||
return cachedRelativePaths.stream()
|
||||
.map(root::resolve)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
List<Path> scannedPaths = lightspeed$scanFilePaths(root);
|
||||
lightspeed$getRelativeFilePathsMap(packType).put(resourceNamespace, lightspeed$toRelativePaths(root, scannedPaths));
|
||||
return scannedPaths;
|
||||
});
|
||||
}
|
||||
|
||||
@Unique
|
||||
@@ -252,6 +271,11 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
|
||||
return lightspeed$filePathsByRoot().computeIfAbsent(packType, ignored -> Maps.newConcurrentMap());
|
||||
}
|
||||
|
||||
@Unique
|
||||
private Map<String, List<String>> lightspeed$getRelativeFilePathsMap(PackType packType) {
|
||||
return lightspeed$relativeFilePaths().computeIfAbsent(packType, ignored -> Maps.newConcurrentMap());
|
||||
}
|
||||
|
||||
@Unique
|
||||
public void lightspeed$cacheNamespaces(PackType packType, Set<String> namespaces) {
|
||||
lightspeed$namespaces().put(packType, namespaces);
|
||||
@@ -287,6 +311,17 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
|
||||
return lightspeed$filePathsByRootByPackType;
|
||||
}
|
||||
|
||||
@Unique
|
||||
private Map<PackType, Map<String, List<String>>> lightspeed$relativeFilePaths() {
|
||||
if (lightspeed$relativeFilePathsByPackType == null) {
|
||||
lightspeed$relativeFilePathsByPackType = Maps.newConcurrentMap();
|
||||
for (PackType packType : PackType.values()) {
|
||||
lightspeed$relativeFilePathsByPackType.put(packType, Maps.newConcurrentMap());
|
||||
}
|
||||
}
|
||||
return lightspeed$relativeFilePathsByPackType;
|
||||
}
|
||||
|
||||
@Unique
|
||||
private List<Path> lightspeed$scanFilePaths(Path root) {
|
||||
try (Stream<Path> stream = Files.find(root, Integer.MAX_VALUE, (candidate, attributes) -> attributes.isRegularFile())) {
|
||||
@@ -299,6 +334,16 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR
|
||||
}
|
||||
}
|
||||
|
||||
@Unique
|
||||
private static List<String> lightspeed$toRelativePaths(Path root, List<Path> paths) {
|
||||
String separator = root.getFileSystem().getSeparator();
|
||||
return paths.stream()
|
||||
.map(root::relativize)
|
||||
.map(Path::toString)
|
||||
.map(path -> path.replace(separator, "/"))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@Unique
|
||||
private Set<String> lightspeed$scanNamespaces(PackType type) {
|
||||
try {
|
||||
|
||||
@@ -18,6 +18,7 @@ public class CacheUtil {
|
||||
SharedConstants.getCurrentVersion().getId()).toFile();
|
||||
public static final File HAS_RESOURCE_CACHE_DIR = new File(CACHE_DIR, "hasResource");
|
||||
public static final File NAMESPACE_CACHE_DIR = new File(CACHE_DIR, "namespaces");
|
||||
public static final File RESOURCE_LIST_CACHE_DIR = new File(CACHE_DIR, "resourceLists");
|
||||
|
||||
public static Stream<File> getCacheFiles(File dir) {
|
||||
if (!dir.isDirectory()) {
|
||||
|
||||
Reference in New Issue
Block a user