From 6fd505c8677b3cb55194cbbce5ac827acd7ea9d4 Mon Sep 17 00:00:00 2001 From: kltyton Date: Thu, 2 Jul 2026 04:57:56 +0800 Subject: [PATCH] Fix resource lookup concurrency --- .../lightspeed/cache/GlobalCache.java | 20 ++- .../lightspeed/config/LightspeedConfig.java | 4 +- .../FallbackResourceManagerMixin.java | 153 ++++++++++++++++++ ...lbackResourceManagerPackEntryAccessor.java | 23 +++ .../resources/PathResourcePackMixin.java | 53 +++++- .../ccr4ft3r/lightspeed/util/CacheUtil.java | 1 + src/main/resources/lightspeed.mixins.json | 2 + 7 files changed, 247 insertions(+), 9 deletions(-) create mode 100644 src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FallbackResourceManagerMixin.java create mode 100644 src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FallbackResourceManagerPackEntryAccessor.java diff --git a/src/main/java/com/ccr4ft3r/lightspeed/cache/GlobalCache.java b/src/main/java/com/ccr4ft3r/lightspeed/cache/GlobalCache.java index 394f619..85e1a2d 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/cache/GlobalCache.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/cache/GlobalCache.java @@ -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 CACHES = Sets.newConcurrentHashSet(); public static final Map> PERSISTED_EXISTENCES_BY_MOD = Maps.newConcurrentMap(); public static final Map>> PERSISTED_NAMESPACES_BY_MOD = Maps.newConcurrentMap(); + public static final Map>>> 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>> futures = new ArrayList<>(packs.size()); @@ -136,6 +141,7 @@ public class GlobalCache { List> 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); + } } diff --git a/src/main/java/com/ccr4ft3r/lightspeed/config/LightspeedConfig.java b/src/main/java/com/ccr4ft3r/lightspeed/config/LightspeedConfig.java index e41c6ab..095af52 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/config/LightspeedConfig.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/config/LightspeedConfig.java @@ -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(); diff --git a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FallbackResourceManagerMixin.java b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FallbackResourceManagerMixin.java new file mode 100644 index 0000000..dc01a28 --- /dev/null +++ b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FallbackResourceManagerMixin.java @@ -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 lightspeed$createStackMetadataFinder(ResourceLocation location, int index); + + @Invoker("createResource") + private static Resource lightspeed$createResource(PackResources pack, ResourceLocation location, + IoSupplier resource, + IoSupplier metadata) { + throw new AssertionError(); + } + + @Inject(method = "getResource", at = @At("HEAD"), cancellable = true) + private void getResourceHeadInjected(ResourceLocation location, CallbackInfoReturnable> cir) { + if (!GlobalCache.isEnabled || !GlobalCache.shouldParallelizeResourcePackLookup || this.fallbacks.size() <= 1) { + return; + } + + List 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 = lightspeed$searchSafeSegment(safeSegment, location); + if (resource != null) { + cir.setReturnValue(resource); + return; + } + safeSegment.clear(); + + if (packResources != null) { + IoSupplier 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 = lightspeed$searchSafeSegment(safeSegment, location); + cir.setReturnValue(resource == null ? Optional.empty() : resource); + } + + @Unique + private Optional lightspeed$searchSafeSegment(List segment, ResourceLocation location) { + if (segment.isEmpty()) { + return null; + } + if (segment.size() == 1) { + IndexedPack indexedPack = segment.get(0); + IoSupplier 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>> 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 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 lightspeed$searchSafeSegmentSequential(List segment, ResourceLocation location) { + for (IndexedPack indexedPack : segment) { + IoSupplier 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) { + } +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FallbackResourceManagerPackEntryAccessor.java b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FallbackResourceManagerPackEntryAccessor.java new file mode 100644 index 0000000..2821a7c --- /dev/null +++ b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/FallbackResourceManagerPackEntryAccessor.java @@ -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 lightspeed$filter(); + + @Invoker("isFiltered") + boolean lightspeed$isFiltered(ResourceLocation location); +} diff --git a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/PathResourcePackMixin.java b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/PathResourcePackMixin.java index 5446148..608b223 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/PathResourcePackMixin.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/mixin/resources/PathResourcePackMixin.java @@ -50,6 +50,9 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR @Unique private Map>> lightspeed$filePathsByRootByPackType; + @Unique + private Map>> 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 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 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 cachedRelativePaths = lightspeed$getRelativeFilePathsMap(packType).get(resourceNamespace); + if (cachedRelativePaths != null) { + return cachedRelativePaths.stream() + .map(root::resolve) + .collect(Collectors.toList()); + } + List 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> lightspeed$getRelativeFilePathsMap(PackType packType) { + return lightspeed$relativeFilePaths().computeIfAbsent(packType, ignored -> Maps.newConcurrentMap()); + } + @Unique public void lightspeed$cacheNamespaces(PackType packType, Set namespaces) { lightspeed$namespaces().put(packType, namespaces); @@ -287,6 +311,17 @@ public abstract class PathResourcePackMixin implements IPathResourcePack, IPackR return lightspeed$filePathsByRootByPackType; } + @Unique + private Map>> 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 lightspeed$scanFilePaths(Path root) { try (Stream 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 lightspeed$toRelativePaths(Path root, List 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 lightspeed$scanNamespaces(PackType type) { try { diff --git a/src/main/java/com/ccr4ft3r/lightspeed/util/CacheUtil.java b/src/main/java/com/ccr4ft3r/lightspeed/util/CacheUtil.java index 12f131f..1bb68fa 100644 --- a/src/main/java/com/ccr4ft3r/lightspeed/util/CacheUtil.java +++ b/src/main/java/com/ccr4ft3r/lightspeed/util/CacheUtil.java @@ -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 getCacheFiles(File dir) { if (!dir.isDirectory()) { diff --git a/src/main/resources/lightspeed.mixins.json b/src/main/resources/lightspeed.mixins.json index 5c7704f..df0afe4 100644 --- a/src/main/resources/lightspeed.mixins.json +++ b/src/main/resources/lightspeed.mixins.json @@ -18,6 +18,8 @@ "misc.StateDefinitonMixin", "resources.AbstractPackResourcesMixin", "resources.DelegatingResourcePackMixin", + "resources.FallbackResourceManagerMixin", + "resources.FallbackResourceManagerPackEntryAccessor", "resources.FilePackResourcesMixin", "resources.PathResourcePackMixin", "resources.SimpleReloadInstanceMixin",